字符指针的动态内存分配

Dynamic Memory allocation for char pointer

本文关键字:内存 分配 动态 指针 字符      更新时间:2023-10-16

我有一个与字符指针的动态内存分配相关的奇怪问题。 我有类似的东西

char *input = new char; //1
gets(input) //2
char *dest = new char; //3

在 Step3 期间,我在运行时收到堆损坏错误。仅当我输入的字符串长度超过 23 个字符时,才会发生这种情况。

如果我不做任何新操作,那么就没有问题。

如果我指定,此问题已解决

char *input = new char[100];

But i want the input to be dynamic based on the user's input.

I am not sure what is the role of 24 bytes in this case. I dont want to limit to 100 or some n characters... I am kinda weak in memory allocation...Can somebody explain this scenario?

No, you can't do that way. You could use only static buffer or use "cpp-way", which is:

std::string str;
std::getline(std::cin, str);

程序在长度大于零的任何输入上表现出未定义的行为,因为gets添加了 null 终止符。该程序不会崩溃多达 23 个字符的事实是一个不幸的巧合。

如果要动态分配缓冲区,请不要使用基于getschar的输入;而是将数据读入std::string

如果您不知道用户将输入的长度,并且不想限制用户输入,则必须分配足够长度的缓冲区。您可以使用 STL 字符串,但它也会动态为您分配足够的内存,它只是隐藏程序的分配详细信息。

永远不要使用gets()(来自手册页):

不执行缓冲区溢出检查

根据输入的内容,您会得到缓冲区溢出。

new char

为一个字符分配内存。它可能会在第二个字符之后失败(实际上即使在第一个字符之后,因为你会得到一个"\0"字符。

如果您将问题标记为C++,请使用C++,而不是 C!这意味着使用 std::string