删除指针导致堆损坏
Deleting pointer causes heap corruption
有人可以解释为什么这段代码会导致堆损坏吗?
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'字符。
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
它定位了错误的来源。
有人可以解释为什么这段代码会导致堆损坏吗?
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'字符。
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
它定位了错误的来源。