1

I am learning C in university now. I want to get the input from the user and then print it on screen. I tried scanf and fgets and both of them crash. Please help i need to learn how to get the input and then print it.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  char name[256];
  printf("Write something:\n");
  gets(name);
  printf("You wrote: %s", name) ;
  return 0;
}
Manuel Pap
  • 1,309
  • 7
  • 23
  • 52
  • 2
    The above code [won't crash](http://ideone.com/EVHS3S) unless there's a buffer overflow, avoid using `gets` – P0W Oct 12 '13 at 08:08
  • Because its the only that doesnt crash ....sorry !I really searched the stackoverflow many hours and i didn't find a similar problem with mine. – Manuel Pap Oct 12 '13 at 08:38

2 Answers2

3

gets is dangerous and deprecated:

Since the user cannot specify the length of the buffer passed to gets(), use of this function is discouraged. The length of the string read is unlimited. It is possible to overflow this buffer in such a way as to cause applications to fail, or possible system security violations.

Use fgets instead:

fgets(name, 256, stdin);

or

fgets(name, sizeof(name), stdin);

and it won't crash (even if you type more than 255 chars)

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

Never use gets. It offers no protections against a buffer overflow vulnerability (that is, you cannot tell it how big the buffer you pass to it is, so it cannot prevent a user from entering a line larger than the buffer and clobbering memory).
gets() doesn't allow you to specify the length of the buffer to store the string in. This would allow people to keep entering data past the end of your buffer.
fgets will always read the new-line if the buffer was big enough to hold it (which lets you know when the buffer was too small and there's more of the line waiting to be read).

haccks
  • 104,019
  • 25
  • 176
  • 264