Hi,
I'm a newbie. I need to clear my pointer concepts.
the code below gives segmentation fault when i use char* str;
int main()
{
char *str;
printf("Enter a string to reverse\n");
scanf("%s",&str );
strlen(str);
}
if I use char str[20] it runs fine.
int main()
{
char str[20];
printf("Enter a string to reverse\n");
scanf("%s",&str );
strlen(str);
}
Can you please explain why?
Thanks 31 3728
Newbie wrote: Hi,
I'm a newbie. I need to clear my pointer concepts.
the code below gives segmentation fault when i use char* str; int main()
use: int main(void) { char *str; printf("Enter a string to reverse\n"); scanf("%s",&str );
Here's the problem. str points to somewhere in memory
but you have no idea where and whether or not that area
belongs to you. You need to allocate memory (dynamically).
You can run into the problem again if you read more
characters than you allocated. strlen(str);
return something. }
if I use char str[20] it runs fine.
Well, yes, because you str[20] is automatically
allocated and you tell it exactly how much memory
you want. To dynamically allocate memory you need
to use a pointer and allocate memory for it (malloc & co). int main()
int main(void) { char str[20]; printf("Enter a string to reverse\n"); scanf("%s",&str ); strlen(str);
return something }
Can you please explain why?
That's it.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Nelu wrote: Newbie wrote: int main() use: int main(void) { char *str; printf("Enter a string to reverse\n"); scanf("%s",&str ); Here's the problem. str points to somewhere in memory but you have no idea where and whether or not that area belongs to you. You need to allocate memory (dynamically). You can run into the problem again if you read more characters than you allocated.
Another problem, as big as not allocating any space for the string, is
that scanf("%s",...) requires `char*`, and you give it `char**`. You
(OP) used `&str` which yields the address of `str` variable, /not/ the
string it points to (even if one exists).
You don't seem to have high enough compiler warning setting, or you
ignored the one you got. My gcc complained...
The badness can be masked also if you just quickly test with the string
that will fit into the sizeof(char*) on your system (it would break
later, when you try to use now broken pointer). strlen(str); return something. }
if I use char str[20] it runs fine. Well, yes, because you str[20] is automatically allocated and you tell it exactly how much memory you want. To dynamically allocate memory you need to use a pointer and allocate memory for it (malloc & co). int main() int main(void) { char str[20]; printf("Enter a string to reverse\n"); scanf("%s",&str ); strlen(str); return something }
Can you please explain why?
Here, you have exactly the same problem as above. Use `str` and not
`&str` for scanf(). Don't get confused by other types. Revisit your
textbook sections on pointers and C strings.
That's it.
Indeed.
--
BR, Vladimir
"OK, now let's look at four dimensions on the blackboard."
-- Dr. Joy
elu wrote: You can run into the problem again if you read more characters than you allocated.
I agree with you on that.
But the codes below works even if you input more than 10 characters?
Why?
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char *str;
str = new char[10];
printf("Enter a string to reverse\n");
scanf("%s",str) ;
cout << strlen(str)<< endl;
system("pause") ;
return 0;
} ge*****@hotmail .com wrote: elu wrote: You can run into the problem again if you read more characters than you allocated.
I agree with you on that. But the codes below works even if you input more than 10 characters? Why?
#include <cstdio> #include <cstring> #include <iostream> using namespace std; int main() { char *str; str = new char[10]; printf("Enter a string to reverse\n"); scanf("%s",str) ; cout << strlen(str)<< endl; system("pause") ; return 0; }
I don't know, it's not C!
Please post C++ questions to comp.lang.c++
<OT>
I don't see why would it work for more characters than you allocate.
</OT>
--
BR, Vladimir
Goto, n.:
A programming tool that exists to allow structured programmers
to complain about unstructured programmers.
-- Ray Simard
Vladimir S. Oka wrote: Nelu wrote: Newbie wrote: int main() use: int main(void) { char *str; printf("Enter a string to reverse\n"); scanf("%s",&str ); Here's the problem. str points to somewhere in memory but you have no idea where and whether or not that area belongs to you. You need to allocate memory (dynamically). You can run into the problem again if you read more characters than you allocated.
Another problem, as big as not allocating any space for the string, is that scanf("%s",...) requires `char*`, and you give it `char**`. You (OP) used `&str` which yields the address of `str` variable, /not/ the string it points to (even if one exists).
You don't seem to have high enough compiler warning setting, or you ignored the one you got. My gcc complained...
The badness can be masked also if you just quickly test with the string that will fit into the sizeof(char*) on your system (it would break later, when you try to use now broken pointer).
Right, I forgot to tell him that, and that if he uses an array
& will have the same address and wouldn't crash the program.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...) ge*****@hotmail .com wrote: elu wrote: You can run into the problem again if you read more characters than you allocated.
I agree with you on that. But the codes below works even if you input more than 10 characters? Why?
#include <cstdio> #include <cstring> #include <iostream> using namespace std; int main() { char *str; str = new char[10]; printf("Enter a string to reverse\n"); scanf("%s",str) ; cout << strlen(str)<< endl; system("pause") ; return 0; }
This is not C. It is C++.
Also, some OSes (or kernel patches) try to avoid buffer overflows
and won't crash the program. However, don't trust them. It's wrong.
I had the same problem with someone who wrote a shell on RedHat a few
years ago and it was working just fine on his machine but crashed
instantly on my slackware. When I checked the code I was stunned.
He was using pointers without allocating any memory for them. His
kernel was patched to deal with buffer overflows so, even if his
program was way wrong it was not crashing. That's not normal behavior.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Nelu wrote: Also, some OSes (or kernel patches) try to avoid buffer overflows and won't crash the program. However, don't trust them. It's wrong.
This sounds absolutely /horrible/!
--
BR, Vladimir
Song Title of the Week:
"They're putting dimes in the hole in my head to see the change
in me."
Nelu said: Vladimir S. Oka wrote: Another problem, as big as not allocating any space for the string, is that scanf("%s",...) requires `char*`, and you give it `char**`. You (OP) used `&str` which yields the address of `str` variable, /not/ the string it points to (even if one exists).
You don't seem to have high enough compiler warning setting, or you ignored the one you got. My gcc complained...
The badness can be masked also if you just quickly test with the string that will fit into the sizeof(char*) on your system (it would break later, when you try to use now broken pointer). Right, I forgot to tell him that, and that if he uses an array & will have the same address and wouldn't crash the program.
Quibble: given char arr[20], arr (in a value context) has type char *,
whereas &arr has type char (*)[20] - these are different and incompatible
types.
More importantly: what nobody seems to have mentioned is that scanf("%s" is
a remarkably dangerous construct, in that it offers no buffer protection
whatsoever.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Richard Heathfield wrote: Quibble: given char arr[20], arr (in a value context) has type char *, whereas &arr has type char (*)[20] - these are different and incompatible types.
Yes. This was discussed on the list recently, I think. More importantly: what nobody seems to have mentioned is that scanf("%s" is a remarkably dangerous construct, in that it offers no buffer protection whatsoever.
I think I told the OP about the problem if the buffer overflows.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: firegun9 |
last post by:
Hello everyone,
here is my program:
///////////////////////////////
#include <iostream>
using namespace std;
void multi(double* arrayPtr, int len){
for(int i=0; i<len; i++)
*(arrayPtr+i)*=2;
|
by: DamonChong |
last post by:
Hi,
I am still struggling to master C++ and is trying to understand how to
achieve passing arguments using pointers. I got some questions that I
like to post to the experts here, hope you can help to clarify my
doubts. I'm using g++ version 3.3.4. I created 3 classes as below for
testing some concepts. The questions are written as comments in
Bclass.h file. Thank you for your time and tips!
------------runtime errors------------
|
by: Foobarius Frobinium |
last post by:
Please review this guide for clarity, accuracy, etc. so I can
hopefully compile a very good tutorial on how to use pointers in C,
including advanced topics, that is easy to follow and exposes the
details.
http://thelinuxlink.net/~fingolfin/pointer-guide/
My e-mail address is fake. To really contact me, send mail to:
fingolfinJOHNLENNONSPENIS@thelinuxlink.net, subtracting the blatant
anti-spam component.
|
by: Alexei A. Frounze |
last post by:
Hi all,
I have a question regarding the gcc behavior (gcc version 3.3.4).
On the following test program it emits a warning:
#include <stdio.h>
int aInt2 = {0,1,2,4,9,16};
int aInt3 = {0,1,2,4,9};
|
by: aegis |
last post by:
The following was mentioned by Eric Sosman
from
http://groups.google.com/group/comp.lang.c/msg/b696b28f59b9dac4?dmode=source
"The alignment requirement for any type T must be a
divisor of sizeof(T). (Proof: In `T array;' both
`array' and `array' must be correctly aligned.)
Since `sizeof(unsigned char)' is divisible only by one
and since one is a divisor of every type's size, every
type is suitably aligned for `unsigned char'."
| |
by: gk245 |
last post by:
I have something like this:
#include <stdio.h>
main ()
{
struct line
{
char write;
char read;
|
by: sara |
last post by:
Hi All,
I think one the most difficult concepts in C++ in pointer handling. Do
you know any good and complete refrence which learn me this topic well?
Thanks a lot.
|
by: ali |
last post by:
Hi,
When I pass a pointer as an argument of a method, is it safe if I
change the data pointed by the argument and return it upon
completion ?
For example:
Object* someFunction(Object* ob)
{
|
by: Summercool |
last post by:
Can we confirm the following? also someone said, Java also has
"reference" like in C++, which is an "implicit pointer":
Pointer and Reference
---------------------
I am starting to see what pointer and reference are and how they
relate
to each other.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |