简体   繁体   中英

Segmentation fault inside printf statement

I get a Segmentation fault inside the insert function within the printf statment

#include <stdio.h>
#include <stdlib.h>
void Insert(char w[])
{
int j;
int n=5;
printf("word is %s AFTER\n", w);
}


int main(int argc, char *argv[])
{
        FILE *fp;
        if (argc !=2)
                fp=fopen("words.txt", "r");
        else
                fp=fopen(argv[1], "r");
        char line[28];
        while(!feof(fp)){
                fgets(line, 256, fp);
                Insert(line);
        }
}

in word.txt its just a bunch of words on each line ie

apple
banana
...
zoo

(... just means a bunch of words in between) it prints this:

word is apple
AFTER
word is banana
AFTER
...(a bunch more repetitions)                                    
word is cookie
Segmentation Fault(core dumped)

Why is there a segmentation fault? it printed the word perfectly. And it didn't print the AFTER

Thanks.

Allocated memory only 28 bytes where as trying to copy 256 byte.

char line[28]; <-- 28 bytes only allocated to line.
        while(!feof(fp)){
                fgets(line, 256, fp); <-- 256 bytes read into line.

Increase the memory for line to avoid this issue.

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