2011-06-19 41 views
1

在gcc上编译后运行下面的代码时,出现段错误。在GCC编译器中使用strupr(...)时的分段错误

#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("%s\n%s\n",e1.n,e2.n); 
    return(0); 
} 

回答

4

"David"的字符串文字不能被改变,这是当你调用strupr你在做什么。您应该先复制字符串(例如strdup)。

+0

值得补充的是,有一个GCC警告选项来发现这个问题,-Wwrite-strings。 –

1

你得到一个赛格故障,因为

struct emp e1={"David",23}; 

“大卫”驻留在数据,所以它是一个只读的,或常量,字符串。

当你

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; 
0

这样做struct emp e1={"David",23};你做“万人迷”字符串文字,它是只读性质的。在可执行文件中,它存储在.rodata或可执行文件的等效部分中,该部分是只读的。通过strupr(),您试图修改此只读数据,从而导致分段错误。