【发布时间】:2015-08-14 06:22:06
【问题描述】:
我已经筋疲力尽地在谷歌上搜索了这个,但我无法找到明确的答案或帮助自己理解出了什么问题。作为家庭作业的一部分,我正在尝试为字符数组(即 CString)动态分配内存并分配一个 char 指针变量指向它,然后在结束程序之前删除分配的内存。我只是把头绕在指针上,所以我怀疑我对幕后发生的事情的一些理解是不正确的,我最终会使用 Visual Studio 2010 给我堆损坏断点。
这是我正在尝试做的事情的简化版本(我的 cmets 表明我认为我正在做的事情):
char *chPtr = new char[10]; // Create a char pointer type variable, and point it at the memory allocated for a char array of length 10
chPtr = "September"; // Assign 9 characters (+1 null terminator character) to the char array
cout << chPtr; // Prints "September", then finds the null terminator and stops printing
delete [] chPtr; // THIS is what causes my heap corruption -> But I don't know why. Shouldn't this delete the array of memory that chPtr is pointing at?
- 我也尝试过使用
delete chPtr,但堆损坏结果相同。 - 我尝试手动将空终止符分配给数组
chPtr[9] = '\0';的末尾,但这也会导致堆损坏。为什么?当我执行cout << chPtr[7];等操作时,我可以从数组中访问单个字符而不会出现任何问题...
真正令人困惑的是,这可以正常工作:
char *chPtr = new char[10]; // As above, create a char pointer type and point it at the memory allocated for a char array of length 10
delete chPtr; // This doesn't give any error!
似乎通过分配一个值来初始化数组对我来说是一种破坏。
谁能帮帮我?
【问题讨论】:
标签: c++ arrays pointers c-strings