无法删除动态分配的char数组 [英] Trouble deleting dynamically allocated char array
问题描述
我收到错误消息:
检测到堆损坏:在0x003B98D0的正常块(#247)之后.
CRT检测到应用程序在堆缓冲区结束后写入了内存.
这是导致问题的函数:
I''m getting the error:
HEAP CORRUPTION DETECTED: After Normal block (#247) at 0x003B98D0.
CRT detected that the application wrote to memory after end of heap buffer.
Here''s the function that''s causing the problem:
String ^data::getItemNumber_noRev()
{
int count = 0;
while(itemNumber[count] != '_')
count++;
char *itemNum_noRev = new char[count];
for(int i = 0; i < count; i++)
itemNum_noRev[i] = itemNumber[i];
itemNum_noRev[count] = '\0';
gcroot<String ^> itemNum_noRev_system = gcnew String(itemNum_noRev);
delete [] itemNum_noRev;
return itemNum_noRev_system;
}
基本上,它通过char数组(例如12324736-1_6)进行处理,其中下划线之前的所有内容都是项目编号,其后是其修订版本.它以System :: String ^的形式返回,因为我正在Windows窗体中使用它.我遇到的问题是:
Basically it goes through a char array such as 12324736-1_6, where everything up to the underscore is the item number, and after is its revision. It is returned as a System::String^ because I''m using it in a Windows Form. The problem I''m having is with the line:
itemNum_noRev[count] = ''\0'';
当我不包括这一行时,我没有收到错误,但是在字符串的末尾我得到了大约10个魔术字符.当我包含该行时,就是当我得到堆损坏错误时.
有什么想法可以解决此问题吗?预先感谢您的任何建议!
Pat
When I don''t include this line, I don''t get an error, but I get about 10 magic characters at the end of my String. When I do include the line, that''s when I get the heap corruption error.
Any ideas what to do to fix this? Thanks in advance for any advice!
Pat
推荐答案
count是最后一个索引之后的1,因为它的索引为0.因此,将大小计数为+1,您将有空间容纳空终止符.
count is one past the last index, because it''s 0 indexed. So make the size count+1, and you''ll have room for your null terminator.
这篇关于无法删除动态分配的char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!