在gcc上编译后运行以下代码时,出现分段错误。
#include <stdio.h>
#include <string.h>
int main(void)
{
struct emp
{
char *n;
int age;
};
struct emp e1={"David",23};
struct emp e2=e1;
strupr(e2.n);
printf("%sn%sn",e1.n,e2.n);
return(0);
}
不能更改像"David"
这样的字符串文字,这就是调用strupr
时要做的。您应该在之前复制字符串(例如使用strdup
)。
由于
struct emp e1={"David",23};
"David"驻留在数据中,因此它是只读或常量字符串。
当你
strupr(e2.n);
您正试图修改相同的常量字符串。
工作代码:
struct emp e2;
e2.age = e1.age;
e2.n = (char *)malloc(SOME_SIZE);
strcpy(e2.n, e1.n); //here you copy the contents of the read-only string to newly allocated memory
strupr(e2.n);
printf(...);
free(e2.n);
return 0;
通过执行struct emp e1={"David",23};
,您使"David"成为一个字符串文字,它本质上是只读的。在可执行文件中,它存储在只读的.rodata
或可执行文件的等效部分中。通过strupr ()
,您正试图修改此只读数据,从而导致分段错误。