Reputation: 145
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.
Upvotes: -1
Views: 75
Reputation: 25
gets(str);
It shouldnt work even in turbo c++ because you have not allocated the space to str. correct way
str = (char *)malloc(sizeof(char) * (length+1));
Upvotes: 0
Reputation: 140287
that
char *str;
gets(str);
just cannot be right. str
is not initialized, and gets
recieves the pointer by value so it cannot allocate it internally. You're just lucky/unlucky with undefined behaviour.
which one is authentic and a more correct form of coding ?
None of the above. don't use gets
. It's unsafe because you cannot limit the input size. Use fgets
with specified size (and an allocated buffer of course!)
#include <stdio.h>
char buffer[20];
fgets(buffer, sizeof(buffer), stdin); // reads at most 19 chars + null-termination
or scanf
with size limit (note the -1): scanf("%19s",buffer);
Upvotes: 0