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 password
by either (1) declaring password
as a stack array:
char password[1024];
or (2), allocate a memory buffer using malloc
:
char *password = malloc(1024);
If you use malloc
, remember that anything you allocate with malloc
must be deallocated with a corresponding call to free
.
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:
scanf(" %[^\n]", password);
Notice there is no &
before password
. You don't need it because password
is a pointer. Placing the &
before password
means 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. scanf
does 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 as fgets
.