简体   繁体   English

C strcpy导致分段错误

[英]C strcpy causing segmentation fault

I have this struct: 我有这个结构:

typedef struct occurrenceType Occurrence;

struct occurrenceType {
char* line;
int lineNumber;
int wordNumber;
Occurrence *next;

}; };

That I'm attempting to create a linked list with like this: 我正在尝试使用以下方式创建链接列表:

inFile=fopen(argv[1],"r");
while(fgets(line,100,inFile)!=NULL) {
    if(strstr(line,argv[2])!='\0') {
            strcpy((*occur).line,line);
                (*occur).lineNumber=count;
                (*occur).next=(Occurrence*)malloc(sizeof(Occurrence));
                occur=(*occur).next;
        lineCount++;
    }
    count++;
}

The program is supposed to read lines of a program and search for a string specified in the command line. 该程序应该读取程序的行并搜索在命令行中指定的字符串。 When a match is found, an occurrence is added to the linked list. 当找到匹配项时,将出现项添加到链接列表中。 Everything works correctly except for the 'line' field of the struct. 除结构的“行”字段外,其他所有内容均正常运行。 When using strcpy to populate it, a segmentation fault occurs, but 使用strcpy进行填充时,会发生分段错误,但是

(*occur).line=line;

is not a viable option because the line pointer changes throughout the program. 这不是一个可行的选择,因为行指针在整个程序中都会改变。 Can anyone suggest an alternate way to do this? 任何人都可以建议另一种方法吗? Thanks! 谢谢!

You need to allocate space for the line field or make it an actual character buffer. 您需要为行字段分配空间或使其成为实际的字符缓冲区。

If you're going to allocate, add this line just above the strcpy in the block: 如果要分配,请在代码块的strcpy上方添加以下行:

    occur->line = calloc( 1, 100 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM