Obtenção de falha de segmentação
Vi muitas perguntas sobregetting segmentation fault no programa C aqui no SO, e pensei que seria ótimo ter uma referência àqueles aqui, uma pergunta com alguns casos que estão causando falha de segmentação. Minha resposta está publicada abaixo.
Conforme escrito em algumas respostas, o comportamento é indefinido para todos os casos, embora muitas pessoas os encontrem comofalha de segmentaçã, então esta pergunta é sobre o que causa esse "sintoma"
Nos casos abaixo, recebo uma falha de segmentação ao executar o programa, você pode determinar o porqu
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