问题
This code gives me a segmentation fault:
char *s1 = "String 1", *s2 = "String 2";
void swap(char **, char **);
int main(void) {
swap(&s1, &s2);
return 0;
}
void swap(char **p, char **q) {
char **tmp;
*tmp = *p;
*p = *q;
*q = *tmp;
}
But if I change the body of the last function to this code it doesn't make any problems:
char *tmp;
tmp = *p;
*p = *q;
*q = tmp;
I really don't understand why am I getting a segmentation fault with the first code. Thanks in advance.
回答1:
Your tmp pointer is uninitialized and you dereference it in the very next line. That's undefined behaviour, which includes the possibility of a segfault.
来源:https://stackoverflow.com/questions/15844783/why-do-i-get-a-segmentation-fault-with-this-c-code