0

When I use char* to store a name without calloc, it will have a error at run-time:

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

using namespace std;

int main()
{
  char* name;
  cout << "What's your name? ";
  gets (name);
  cout << "Hello, " << name;
  return 0;
}

It will be not problem when I use:

char* name = (char *) calloc(100, sizeof(char));

Can you tell me why? Thanks,

Joey
  • 135
  • 7
  • You should never have used `gets()` to start with. The reasons are well-documented. Also, you shouldn't have used C-style casts, which are similarly bad. – Ulrich Eckhardt Mar 27 '16 at 07:10

2 Answers2

2
char* name;

That declares name to be a pointer. But it is uninitialized.

gets (name);

Tries to read input into whatever name points to. Since name has not been initialized to point to valid memory, trying to read data into what name points to is undefined behavior. Your program can do anything.

When you use:

char* name = (char *) calloc(100, sizeof(char));

name points to a location that can hold 100 characters. If your input is less than 100 characters (leave one for the terminating null characters), then

gets(name);

will be fine. If the input is 100 or more characters, your program will be subject to undefined behavior again. That's why use of gets is considered a security risk. DON'T USE IT. For further information see Why is the gets function so dangerous that it should not be used?.

Instead, use

fgets(name, 100, stdin);
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Why does it not have any errors when I use `char* name = (char *) calloc(2, sizeof(char));` and `gets(name);` and I inputed a string `abcde` that have strlen is 6? – Joey Mar 27 '16 at 11:47
  • @Joey, that is still undefined behavior. Unfortunately, seemingly sane behavior also falls under undefined behavior. – R Sahu Mar 27 '16 at 18:22
0

gets stores sequence of chars in its argument. Thus, you need to allocate that sequence in advance. Otherwise, it will store sequence at the random place in memory where (uninitialized) name points. The lucky case is that the program crashes immediately. In my case, the program works now, which is more dangerous because it can break in the future. Also, this function is considered deprecated, take a look at here.

karastojko
  • 1,156
  • 9
  • 14