This question already has answers here:
Closed 4 years ago.
Segmentation Fault in strcpy()
(3个答案)
我有一个指向我的struct gsa_sentence的指针,它有一个名为char*untouched_sentence类型的结构成员。
我的目标是使用strcpy将一行文件复制到这个struct变量中,但是在strcpy函数调用中出现了分段错误。
结构:
typedef struct gsa_sentence{

    char *untouched_sentence;
    char *sentence_id;
    char mode;
    int fix;
    int sv_1;
    int sv_2;
    int sv_3;
    int sv_4;
    int sv_5;
    int sv_6;
    int sv_7;
    int sv_8;
    int sv_9;
    int sv_10;
    int sv_11;
    int sv_12;
    int pdop;
    int hdop;
    int vdop;

}gsa_sentence;

strcpy调用:
   gsa_sentence* gsa;

   gsa = malloc(sizeof(gsa_sentence));
   printf("%s", line);
    if(gsa != NULL){
       strncpy(gsa->untouched_sentence, line, strlen(line));
       printf("%s", gsa->untouched_sentence);
        }

我在代码中的其他地方使用过strcpy,它工作得很好,我不知道发生了什么。
gdb调试器说它定义在strcpy函数调用上

最佳答案

Strcpy正在尝试将字符复制到未初始化的字符缓冲区中您还需要malloc space foruntouched sentence,”或将untouched sentence重新分配到line的内存地址。
或者,您可以将结构的定义更改为默认情况下包括已分配的内存:

typedef struct gsa_sentence{

    char untouched_sentence[50];
    char sentence_id[50];
...

关于c - 使用strcpy将“字符串”复制到结构成员char *中时出现段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22314329/

10-15 17:55