Sanchke Dellowar Sanchke Dellowar - 3 months ago 15
C Question

C - fgets mysteriously causes segfault when using char arrays

I've seem some similar questions to this one, however I'm asking in a very direct way so hopefully I can get a good explanation as to what the hell is going on.

Look at this very simple program:

int main()
{
char* a;
a[200];
fgets(a, 200, stdin);

char* b;
b[200];
fgets(b, 200, stdin); // Seg fault occurs once I press enter

return 0;
};


As you can see, section 'a' runs fine. however section 'b' seg faults. What is going on?

Answer

Well, this is basics here. A segfault means you are using memory you do not have access to it.

int main()
{
    char* a; // Create a pointer (a pointer can only contains an address (int size)
    a[200]; // Trying to access to the byt 200 of your pointer but basicaly do nothing. You are suppose to have a segfault here

    fgets(a, 200, stdin); // store your stdin into &a (you may have a segfault here too)

    return 0;
};

Depending on many thing, sometimes it may fails, sometimes not. But you are doing something wrong here. You have to way to fix this. First using a simple array char

int main()
{
     char str[200];
     fgets(str, 200, stdin);

     write(1, str, 200);

     return (0);
}

Or if you want to keep using pointers

int main()
{
     char* str;
     str = malloc(sizeof(char) * 200);

     write(1, str, 200);

     fgets(str, 200, stdin);
}

But anyway, your mistake results from a lack of knowledge about pointer and memory in C.

Good luck with that,