使用带有GCC编译器的strupr(...)时出现分段错误

时间:2011-06-19 23:32:36

标签: c

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

3 个答案:

答案 0 :(得分:4)

"David"之类的字符串文字无法更改,这是您拨打strupr时正在执行的操作。您应该在之前复制字符串(例如,使用strdup)。

答案 1 :(得分:1)

你因为

而遇到了段错误
struct emp e1={"David",23};

“David”驻留在数据中,因此它是一个只读或const字符串。

当你

strupr(e2.n);

您正在尝试修改相同的const字符串。

工作代码:

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;

答案 2 :(得分:0)

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