I have the following piece of code:
char *str;
gets(str);
Now it works in turbo c but fails to in devc.
I have to add the following in order to make it work in devC++.
char *str = malloc(5);
Can anyone explain, why is it so?
Also, which one is authentic and a more correct form of coding.
that
just cannot be right.
stris not initialized, andgetsrecieves the pointer by value so it cannot allocate it internally. You're just lucky/unlucky with undefined behaviour.None of the above. don't use
gets. It's unsafe because you cannot limit the input size. Usefgetswith specified size (and an allocated buffer of course!)or
scanfwith size limit (note the -1):scanf("%19s",buffer);