segmentation fault using scanf

You need to initialize your pointers. Alternatively, use stack-allocated arrays.

For example, instead of char *name, do char name[20]. (Note that this will limit your input to 19 characters; use a larger buffer if necessary.)

Right now, you are passing uninitialized pointers into scanf() which effectively means that scanf() is going to write to an undefined area of memory. It might work on one execution and then fail on the next. It might corrupt memory elsewhere in the process’ address space.

Don’t use uninitialized variables, and consider turning up your compiler warnings as high as they will go; the compiler can catch errors like this and emit a warning.

Leave a Comment