I am a beginner with C. This is a simple program that prompts for a name from keyboard input, creates a greeting using the name, then prints it. At runtime, immediately after entering the name at the console and pressing enter, a segmentation fault occurs. After debugging I suspect the fault lies at the scanf() function. I've tried tweaking the argument 'name' with '*' and '&', and initializing the char array 'name' with an empty string, but none of this helped.
// Prompt for a name and print a greeting using the name.
#include <stdio.h>
#include <string.h>
int main()
{
// Prompt for a name.
printf("What is your name? ");
// Get the name.
char name[20];
scanf("%s", name); // Suspect segfault occurs here...
// Construct the greeting.
char *greeting;
char *suffix;
greeting = "Hello, ";
suffix = ", nice to meet you!";
strcat(greeting, name);
strcat(greeting, suffix);
// Display the greeting.
printf("%s", greeting);
return 0;
}
Suspect segfault occurs here...I thought you said you'd run a debugger? That'll make it clear where the segfault is occurring, which isn't there. As mentioned, it's because you're trying to do stuff with constant data, which is UB. Anyway, there's no need to do 2 steps ofchar *c; c = "stuff";when you can simply doconst char c[] = "stuff";- which makes it a lot clearer conceptually that you're dealing with read-only memory here. - underscore_dchar *c; c = "stuff";would bechar * c = "stuff";. What you propose changes the situation significantly. - alkcwould have the same semantics in most cases. But if anything, it seems even better as then you can use it to get thesizeofthe string (including the null terminator). - underscore_dconst. However that's not much of a problem in C, as opposed to C++. Still pointers are not arrays. - alkconstvariable provokes UB. - alk