tgh*_*tgh 1 c++ arrays memory-leaks
所以我有一个创建动态数组的函数,然后在我离开函数之前删除数组(正如我想的那样),但是我在VS2008中收到了"Heap Corruption Detected"警告.如果我删除释放内存的行一切正常:
void myFunc()
{
char* c = new char[length];
memset(c, 0, length);
//.. do somsething with array
delete[] c; //this line throws an error??
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的建议
Most likely you are doing something else bad (like under/overflowing your buffer) and corrupting the heap at that point, but it isn't detected until you call delete[] and try to interpret the now corrupted heap structures.
Post the 'do something' section if you need more assistance.
I think you have a problem with your //.. do something with array code (or even some other code) since the rest of what you have is okay.
Often, memory arena corruption is only detected when freeing the memory which is probably why removing the line seems to fix it.
But rest assured, the arena is still corrupted whether or not you're detecting it. You need to fix it.
One way this might happen is if your memory allocation routines actually allocate extra bits before and possibly after what you're given. For example, if you ask for 1024 bytes, what might actually be allocated from the heap is a 1040-byte block of which you're given the address of the 16th byte. This gives the arena manager 16 bytes at the start to store housekeeping information (including a sentinal value at the very start of it).
Then, when the block is deleted, the arena manager knows that its housekeeping is in the 16 bytes before the address you're trying to free and can check the sentinal value (or all the sentinals in the arena or just the ones on either side of the one you're freeing - this is all implementation detail) to make sure they're unchanged. If they have been changed, that's detected as corruption.
As I said earlier, the corruption couuld be caused by your //.. do something with array code or it could be somewhere totally different - all that matters is that the arena is being trashed.