当我使用 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/