Search code examples
csegmentation-faultmallocfgetsfputs

fgets in fputs gives segmentation fault


I tried the following code and got a segmentation fault-

    int size=30;
    char *str;
    fputs(fgets(str,size,STDIN),STDOUT);

but when i run this as -

    buff=fgets(str,size,STDIN);
    fputs(buff,STDOUT);

it works just fine. Moreover the first code runs if i use malloc for str. I can't understand how this is happening.


Solution

  • Your problem lies here:

    char *str;
    // de-referenece str in ANY way.
    

    You have a pointer which could be pointing anywhere. It is undefined behaviour to access arbitrary memory like that.

    The fact that it works in one case but not the other is purely coincidental, you should be providing a proper buffer like:

    char str[100]; // or whatever size you need.
    

    or using malloc to dynamically allocate memory, as you've already discovered.

    Once you get into the murky world of undefined behaviour, all bets are off.

    It may crash, it may work, it may result in flying pigs or nasal demons or the collapse of your local space-time region into a singularity. Bottom line, don't do it :-)