0

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 i.e.

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.

4
  • 1
    I don't think this is the error but why do you read up to 256 bytes into an array where you only have 28b? Change line[28] to line[256] and see if that helps. Commented Dec 3, 2012 at 7:06
  • 1
    char line[28]; then fgets(line, 256, fp); seems nasty. You can have a very nice solution for this. Commented Dec 3, 2012 at 7:06
  • 2
    char line[28]; => char line[256]; Commented Dec 3, 2012 at 7:08
  • 1
    That's what happens when you try to put 256 pounds of potatoes in a 28 pound bag. Commented Dec 3, 2012 at 7:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

please don't use duplicate constant sizes! I'd suggest using sizeof(line) instead.
@H2CO3: Please, don't clutter the code with superfluous parentheses. sizeof line is sufficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.