字符指针的动态内存分配
Dynamic Memory allocation for char pointer
我有一个与字符指针的动态内存分配相关的奇怪问题。 我有类似的东西
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 个字符的事实是一个不幸的巧合。
如果要动态分配缓冲区,请不要使用基于gets
或char
的输入;而是将数据读入std::string
。
如果您不知道用户将输入的长度,并且不想限制用户输入,则必须分配足够长度的缓冲区。您可以使用 STL 字符串,但它也会动态为您分配足够的内存,它只是隐藏程序的分配详细信息。
永远不要使用gets()
(来自手册页):
不执行缓冲区溢出检查
根据输入的内容,您会得到缓冲区溢出。
new char
为一个字符分配内存。它可能会在第二个字符之后失败(实际上即使在第一个字符之后,因为你会得到一个"\0"字符。
如果您将问题标记为C++,请使用C++,而不是 C!这意味着使用 std::string
- Win32编译器选项和内存分配
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 当需要超过16GB的连续内存时,内存分配失败
- 尝试摆脱任何堆内存分配
- 以下代码执行哪种内存分配(动态或静态)?
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- C++:矢量分配器行为、内存分配和智能指针
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- Linux C++ 中的页面对齐内存分配
- 整数内存分配/释放
- 将内存分配返回值强制转换为 TYPE 数组
- C++程序什么都不做,但瓦尔格林德显示内存分配
- 给定特定内存地址的数组的动态内存分配
- 如何完成内存分配
- 我刚刚了解了C++中的动态内存分配
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 对于堆上的页面对齐内存分配是否有任何优化或不同的 API?
- 无法删除布尔动态内存分配