c - Getting Segmentation Fault -


i saw many questions getting segmentation fault in c program here in so, , thought great have reference here, question cases causing segmentation fault. answer posted below.

as written in answers, behavior undefined cases, though many people meet them segmentation fault, question causes "symptom".

in cases below segmentation fault when run program, determine why?

1)

char *str = "foo"; str[0] = 'b';   // << segfault hre 

2)

char str[] = "foo"; char *newstr = malloc(strlen(str)); strcpy(newstr, str); free(newstr);   // << segfault here 

3)

char *str = malloc(4 * sizeof(char)); str = "foo"; free(str);      // << segfault here 

4)

char *str = malloc(4 * sizeof(char)); strcpy(str, "foo"); free(str); if (str != null)     free(str);      // << segfault here 

5)

char *str = "something , foo"; printf("%s", str[19]);    // << segfault here 

6)

typedef struct {     char *str; }st; ... st *s; s = malloc(sizeof(st)); s->str = malloc(5); free(s); free(s->str);    // << segfault here 

all examples causing undefined behaviour, might lead crash (or might not appear harm @ all).

  1. you're not allowed change string literal. (see e.g. here)

  2. you forgot allocate storage terminating nul byte, malloc(strlen(str) + 1);

  3. you're calling free() on pointer did not obtain malloc (or similar functions). make str pointer point string literal, you've lost pointer memory allocated malloc , leak memory here too.

  4. you're calling free() twice on same pointer, undefined behavior.

  5. %s in printf format string tells printf argument string (a char * pointing sequence of nul terminated characters) you're passing char, not string. if want print suffix of string use printf("%s", &str[19]);

  6. you're passing in invalid pointer free(), free'd s, can't dereference later when s->str. reverse order of deallocation: free(s->str); free(s);


Comments