简体   繁体   English

为什么我用这个C代码会出现分段错误?

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

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. 提前致谢。

Your tmp pointer is uninitialized and you dereference it in the very next line. 您的tmp指针未初始化,您在下一行中取消引用它。 That's undefined behaviour, which includes the possibility of a segfault. 这是未定义的行为,包括段错误的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM