简体   繁体   中英

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

(*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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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