在下面的程序,SIGSEGV關於修改的char *元素
#include<stdio.h>
#include<stdlib.h>
int main(){
const char *str1 = "abc";
char *str2 = (char *)malloc(sizeof(char)*4);
str2= "def";
str2[1]='s';
printf("str2 is %s", str2);
}
調試器:
(gdb) ptype str1
type = const char *
(gdb) ptype str2
type = char *
(gdb) n
7 str2[1]='s';
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00000000004005ab in main() at main.c:7
7 str2[1]='s';
(gdb)
SIGSEGV上str2[1] = 's';
按我的理解,一個不能修改abc
由st1
指向,由於聲明const char *st1 = "abc"
,其中字符串常量是常量。
爲什麼char *
類型str2
不允許修改元素? stringliteral def
也是一個常量字符串文字。
[不要在C中輸入'malloc'的結果](http://stackoverflow.com/q/605845/995714) –
[改變字符串值拋出分段錯誤](http://stackoverflow.com/q/3550171/995714) –