Possible Duplicate:
segmentation fault using scanf
I am trying to run a C program wherein I accept password from the user and then output it. However, when I run the program I get a message called “Segmentation Fault (core dumped)”. I know that this fault occurs where the array seems to exceed the stack size but I am unable to figure out where I am wrong. Any help is appreciated. The code is as follows:
int main(int argc, char *argv[])
{
int i = 0;
char *password, *key;
int keylength = 256;
printf("\nPlease enter a password: ");
scanf(" %[^\n]", &password);
printf("Entered password is: %s", password);
return 0;
}
You’re not allocating any memory for
password. It’s just an uninitialized pointer. In C you always need to make sure that your pointers point to a valid allocated memory buffer before using them. Using an uninitialized pointer causes undefined behavior, which usually results in crashes.Allocate memory for
passwordby either (1) declaringpasswordas a stack array:or (2), allocate a memory buffer using
malloc:If you use
malloc, remember that anything you allocate withmallocmust be deallocated with a corresponding call tofree.Also, in the code you posted, when you pass your buffer to
scanf, you’re taking the address of the pointer itself when you say&password. What you want to do is simply pass the pointer (which is a memory address referring to your allocated buffer), like:Notice there is no
&beforepassword. You don’t need it becausepasswordis a pointer. Placing the&beforepasswordmeans you’re passing a pointer to a pointer, which is not what you want.Finally, be aware that when programming in C, buffer overflows are a constant danger.
scanfdoes not do anything to prevent the user of your program from entering more data than can fit in the buffer. If this happens, a buffer overflow occurs and your program will exhibit undefined behavior (and probably crash). There are safer ways to take string input from a user, such asfgets.