Why Do I Get a Segmentation Fault with this C Code?

馋奶兔 提交于 2020-01-04 02:48:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!