为什么我得到使用本C code分段错误? [英] Why Do I Get a Segmentation Fault with this C Code?

查看:197
本文介绍了为什么我得到使用本C code分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这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;
}

但是,如果我更改最后一个函数体这个code这没有任何问题:

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;

我真的不明白为什么我得到一个分段错误与第一code。
先谢谢了。

I really don't understand why am I getting a segmentation fault with the first code. Thanks in advance.

推荐答案

TMP 指针未初始化,并取消引用它在非常下一行。这是不确定的行为,其中包括段错误的可能性。

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.

这篇关于为什么我得到使用本C code分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆