调试C时显示Program received signal SIGSEGV, Segmentation fault.

用的codeblocks编译器

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

int main()
{
    char *str=(char *)malloc(6);
    str="hello";
    printf("%s\t%u\n",str,str);
    str=(char *)realloc(str,21);
    strcat(str,"world");
    printf("%s\t%u",str,str);
    free(str);
    return 0;
}

输出结果:
图片描述

debug时报错

clipboard.png
请问是什么原因?

阅读 8.8k
1 个回答

str="hello"; 这个语句将字符串常量"hello"的地址赋值给str, 所以str的地址改变为一个指向常量字符串的地址. 不是malloc的地址, 所以free(str)就会出错.

可以改为:

strcpy(str, "hello");
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进