I saw many questions about getting segmentation fault in C program here in SO, and I thought it would be great to have a reference to those here, a question with some cases that are causing segmentation fault. My answer is posted below.
As written in some answers, the behavior is undefined for all cases, though many people meet them as segmentation fault, so this question is about what causes this "symptom".
In the cases below I get segmentation fault when I run the program, could you 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 and then 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