Can anyone explain why my program crashed when working with char* ???

closed account (3hMz8vqX)
Hi all,
I have a small problem...
when working with char* my program crashes!!!
here is the code:
1
2
3
4
5
6
7
8
ifstream file;
char* text;
file.open("file.txt");
while(file.good())
{
file >> text;
cout << text << endl;
}


I know I could use string in place of char* ...
But, I want to know whats the
problem with char* ...???

Thankyou everyone in advance!!! :)
You didn't initialize it to point to any memory, so as of right now it points to random arbitrary memory, and then you're trying to read into that memory, overwriting was was originally there and (hopefully) getting a segfault.

Also, never use char * for strings, especially for input - the issue is you would have to have a fixed size on the memory you initialize, and if the user inputs more than that fixed size you've got problems.
closed account (3hMz8vqX)
Okay,
Thankyou very much L B!!!
This topic is solved:)
Regards,
Aravind.
Two options:

1
2
3
4
5
6
7
8
ifstream file;
char text[100]; // or a maximum size you would ever expect
file.open("file.txt");
while(file.good())
{
file >> text;
cout << text << endl;
}

1
2
3
4
5
6
7
8
ifstream file;
string text;
file.open("file.txt");
while(file.good())
{
file >> text;
cout << text << endl;
}
Last edited on
closed account (3hMz8vqX)
Okay,
Thankyou Stewbond!!!
and thankyou L B!!!
Thankyou everyone for your help :)
Regards,
Aravind.
Topic archived. No new replies allowed.