c - fgets in fputs gives segmentation fault -



c - fgets in fputs gives segmentation fault -

i tried next code , got segmentation fault-

int size=30; char *str; fputs(fgets(str,size,stdin),stdout);

but when run -

buff=fgets(str,size,stdin); fputs(buff,stdout);

it works fine. first code runs if utilize malloc str. can't understand how happening.

your problem lies here:

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

you have pointer pointing anywhere. undefined behaviour access arbitrary memory that.

the fact works in 1 case not other purely coincidental, should providing proper buffer like:

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

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

once murky world of undefined behaviour, bets off.

it may crash, may work, may result in flying pigs or nasal demons or collapse of local space-time part singularity. bottom line, don't :-)

c segmentation-fault malloc fgets fputs

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -