Segmentation Error - C

Why is the following code returned with a segmentation error? When I comment on line 7, the seg error disappears.

int main(void){ char *s; int ln; puts("Enter String"); // scanf("%s", s); gets(s); ln = strlen(s); // remove this line to end seg fault char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome dyn_s = s; dyn_s[strlen(s)] = '\0'; puts(dyn_s); return 0; } 

Hooray!

+8
c segmentation-fault
source share
5 answers

s is an uninitialized pointer; you write in a random place in memory. This will cause undefined behavior.

You need to allocate some memory for s . Also, never use gets ; There is no way to prevent the memory that you are allocating from being full. Use fgets instead.

+12
source share

Catastrophically bad:

 int main(void){ char *s; int ln; puts("Enter String"); // scanf("%s", s); gets(s); ln = strlen(s); // remove this line to end seg fault char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome dyn_s = s; dyn_s[strlen(s)] = '\0'; puts(dyn_s); return 0; } 

it's better:

 #include <stdio.h> #define BUF_SIZE 80 int main(int argc, char *argv[]) { char s[BUF_SIZE]; int ln; puts("Enter String"); // scanf("%s", s); gets(s); ln = strlen(s); // remove this line to end seg fault char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome dyn_s = s; dyn_s[strlen(s)] = '\0'; puts(dyn_s); return 0; } 

Best:

 #include <stdio.h> #define BUF_SIZE 80 int main(int argc, char *argv[]) { char s[BUF_SIZE]; int ln; puts("Enter String"); fgets(s, BUF_SIZE, stdin); // Use fgets (our "cin"): NEVER "gets()" int ln = strlen(s); char *dyn_s = (char*) malloc (ln+1); strcpy (dyn_s, s); puts(dyn_s); return 0; } 
+2
source share

Your scanf("%s", s); commented out. This means that s is not initialized, so when this line is executed ln = strlen(s); , you get a seg error.

It always helps to initialize a pointer to NULL, and then check for null before using the pointer.

+1
source share

Even better

 #include <stdio.h> int main(void) { char *line = NULL; size_t count; char *dup_line; getline(&line,&count, stdin); dup_line=strdup(line); puts(dup_line); free(dup_line); free(line); return 0; } 
+1
source share
 char *s does not have some memory allocated . You need to allocate it manually in your case . You can do it as follows s = (char *)malloc(100) ; 

This will not result in a segmentation error because you will no longer refer to an unknown location.

+1
source share

All Articles