为什么没有calloc函数我会得到错误运行时?

时间:2016-03-27 06:10:16

标签: c++ gets

当我使用char*存储name而没有calloc时,它会在运行时出错:

#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;
}

使用时不会有问题:

  

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

你能告诉我为什么吗?谢谢,

2 个答案:

答案 0 :(得分:2)

char* name;

宣布name为指针。但它没有初始化。

gets (name);

尝试将输入读入任何name点。由于name尚未初始化为指向有效内存,因此尝试将数据读入name指向的未定义行为。你的程序可以做任何事情。

使用时:

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

name指向可容纳100个字符的位置。如果您的输入少于100个字符(留下一个用于终止空字符),则

gets(name);

会好的。如果输入为100个或更多字符,则程序将再次受到未定义的行为的影响。这就是使用gets被视为安全风险的原因。不要使用它。有关详细信息,请参阅Why is the gets function so dangerous that it should not be used?

相反,请使用

fgets(name, 100, stdin);

答案 1 :(得分:0)

gets在其参数中存储字符序列。因此,您需要提前分配该序列。否则,它会将序列存储在内存中的随机位置(未初始化)name点。幸运的是,该程序立即崩溃。在我的情况下,该程序现在正在运行,这更危险,因为它可能会在未来中断。此外,此功能被视为已弃用,请查看here

相关问题