c++ - 为什么我在没有 calloc 函数的情况下会出现运行时错误?

标签 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));

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

最佳答案

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);

关于c++ - 为什么我在没有 calloc 函数的情况下会出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244420/

相关文章:

没有 libpq++ 和 SQLAPI++ 的 C++ 和 Postgresql

c++ - 找不到版本 GLIBCXX_3.4.11(buildW.mexglx 需要)

c++ - CMake:如何确定可执行文件所需的所有 .DLL/.SO 文件?

c - 为什么这个程序不起作用?

c - 如何在给定代码中接受 C 中字符串中的空格

c - 漏洞利用开发 - GETS 和 Shellcode

c - 禁用警告 : the `gets' function is dangerous in GCC through header files?

c++ - 如何从 QTableWidget 中删除所有行

c++ - gmock 支持右值引用的解决方法

c++ - gets() 正式弃用了吗?