有人可以解释为什么这段代码会导致堆损坏吗?
string someText = "hello hello";
char **arrayOfCharPtr = new char*[5];
arrayOfCharPtr[0] = new char[someText.length()];
strcpy(arrayOfCharPtr[0], someText.c_str());
delete[] arrayOfCharPtr[0];
非常感谢!
答案 0 :(得分:3)
你需要分配一个比字符串长度多的字符来存储最后一个'\ 0'字符。
arrayOfCharPtr[0] = new char[someText.length()+1];
在你的情况下,strcpy将在分配的块之后写下最后一个'\ 0'并且它会破坏堆。
像valgrind这样的工具有助于理解。 valgrind生成错误消息
==16970== Invalid write of size 1
==16970== at 0x4C3106F: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16970== by 0x400C47: main
==16970== Address 0x5ab5cfb is 0 bytes after a block of size 11 alloc'd
==16970== at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16970== by 0x400C1C: main
用于本地化错误源。