为什么以下代码存在分段故障

  • 本文关键字:存在 分段 故障 代码 c
  • 更新时间 :
  • 英文 :


以下代码给出分段错误:

#include <stdio.h>
int main()
{
char* str = "hello world";
str[0] = 'H'; // it is throwing segmentation fault.

printf("%s",str);
return 0;
}
用初始化值定义的char指针进入只读段。要在以后的代码中修改它们,您需要使用malloc()calloc()函数将其存储在堆内存中,或者将它们定义为数组。必须读取

无法更改:

char *ptr1 = "Hello, World!";

可以更改:

char ptr2[] = "Hello, World!";

堆内存示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *str = calloc(14, sizeof(char));
strcpy(str, "Hello, World!");

printf("Before: %sn", str);
str[0] = 'Q';
printf("After: %sn", str);
free(str); // heap-allocated memory must be freed
return EXIT_SUCCESS;
}

数组(堆栈分配内存(示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char str[14] = {}; // decayed to pointer, but `sizeof()` operator treats this as an array in C
strcpy(str, "Hello, World!");

printf("Before: %sn", str);
str[0] = 'Q';
printf("After: %sn", str);

return EXIT_SUCCESS;
}

最新更新