简体   繁体   English

printf语句中的分段错误

[英]Segmentation fault inside printf statement

I get a Segmentation fault inside the insert function within the printf statment 我在printf语句中的插入函数中遇到分段错误

#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 在word.txt中,每行仅是一堆单词,即

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 它没有打印AFTER

Thanks. 谢谢。

Allocated memory only 28 bytes where as trying to copy 256 byte. 分配的内存只有28个字节,试图复制256个字节。

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. 增加内存为line ,以避免此问题。

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

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