加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c程序中的分段错误

发布时间:2020-12-16 03:46:46 所属栏目:百科 来源:网络整理
导读:只是为了测试我创建了以下代码: #includestdio.hint main(){ char *p = "Hello world"; *(p+1) = 'l'; printf("%s",p); return 0;} 但当我在ubuntu 10.04下运行我的“gcc”编译器时,我得到了: Segmentation fault 所以任何人都可以解释为什么会这样. #incl
只是为了测试我创建了以下代码:
#include<stdio.h>

int main(){
    char *p = "Hello world";
    *(p+1) = 'l';
    printf("%s",p);
    return 0;
}

但当我在ubuntu 10.04下运行我的“gcc”编译器时,我得到了:

Segmentation fault

所以任何人都可以解释为什么会这样.

#include<stdio.h>
#include<stdlib.h>

int main(){
    char *p = malloc(sizeof(char)*100);
    p = "Hello world";
    *(p+1) = 'l';
    printf("%s",p);
    free(p);
    return 0;
}

这也会导致分段错误
提前致谢

解决方法

char *p = "Hello world";
*(p+1) = 'l';

修饰字符串文字的内容(即代码中的“Hello World”)是未定义的行为.

ISO C99(第6.4.5 / 6节)

It is unspeci?ed whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array,the behavior is unde?ned.

尝试使用字符数组.

char p[] = "Hello World";
p[1] = 'l';

编辑

你修改过的代码

#include<stdio.h>
#include<stdlib.h>
int main()
{
   char *p = malloc(sizeof(char)*100);
   p = "Hello world"; // p now points to the string literal,access to the dynamically allocated memory is lost.
   *(p+1) = 'l'; // UB as said before edits
   printf("%s",p);
   free(p); //disaster
   return 0;
}

也会调用未定义的行为,因为您正在尝试释放尚未使用malloc分配的内存部分(使用free)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读