segmentation problem

Apr 29, 2009 at 2:18am
Hello i wrote this program, it works perfect, however at the end i have a segmentation fault problem.. can anyone tell me how do i correct that mistake???

int main(){
char* word;
char letter;
int i=0;
printf ("Please enter the word.");
scanf("%s",word);
letter=*word;
while(letter!=0){
printf("%c\n",letter);
i++;
letter=*(word+i);
}
return 0;
}

Thanks in advance...
Last edited on Apr 29, 2009 at 2:19am
Apr 29, 2009 at 2:36am
word doesn't point to a valid address, so when scanf() attempts to write there, the system crashes the program.
Apr 29, 2009 at 1:09pm
Thanks for answering!!!

The program works perfect, but when the program ends the segmentation problem appears.. For example, if i write "hello" the program does the following:
h
e
l
l
o
segmentation fault
Apr 29, 2009 at 1:27pm
word doesn't point to a valid address

Either use dynamic allocation by making word point to new char[something] or use stack allocation by declaring word as char word[something].
Last edited on Apr 29, 2009 at 1:32pm
Apr 29, 2009 at 1:35pm
char* is not a string, it's a pointer. If you want to use it, you have to make it point to something. Right now it's not pointing to anything (or, more accurately, it's pointing to garbage). When you copy a string to it (with scanf), you're corrupting memory, which is what's giving you a segfault.

A solution here is to use a C-style string (char buffer), ie:

 
char word[100];


But note that this method limits how long your word can be (you'll get a segfault if the user inputs a word longer than 99 characters).

A better solution is to use a C++ std::string and C++ iostreams (ie: cin/cout) instead of scanf()/printf(). Using std::string greatly reduces the risk of buffer overflow and segfaults (but doesn't completely protect against them).
Last edited on Apr 29, 2009 at 1:36pm
Topic archived. No new replies allowed.