我是 valgrind 的新手,所以我可能做错了什么,但是如果 valgrind 报告的 frees 比 allocs 多,我该怎么办?
在这里获得了 SSCCE:
#include <cstring>
class something
{
protected:
char* ptr;
public:
something() {ptr = NULL;}
something(const char* value) {
ptr = new char[strlen(value)+1]; strcpy(ptr, value);
}
~something() {delete[] ptr; ptr = NULL;}
};
int main()
{
something x;
x = "123";
return 0;
}
编译得很好,运行也很好,但是 valgrind 说
==15925== Invalid free() / delete / delete[]
==15925== at 0x40221EA: operator delete[](void*) (vg_replace_malloc.c:364)
==15925== by 0x8048689: something::~something() (test.cpp:12)
==15925== by 0x80485F5: main (test.cpp:19)
==15925== Address 0x42b7028 is 0 bytes inside a block of size 4 free'd
==15925== at 0x40221EA: operator delete[](void*) (vg_replace_malloc.c:364)
==15925== by 0x8048689: something::~something() (test.cpp:12)
==15925== by 0x80485E5: main (test.cpp:18)
==15925==
==15925== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 18 from 1)
==15925== malloc/free: in use at exit: 0 bytes in 0 blocks.
==15925== malloc/free: 1 allocs, 2 frees, 4 bytes allocated.
==15925== For counts of detected errors, rerun with: -v
==15925== All heap blocks were freed -- no leaks are possible.
我不确定为什么。
当然,我可以做出有根据的猜测——显然,违规行就是它所说的地方x = "123";
,如果你把它评论出来,一切都很好。但是为什么编译器会认为这没问题,即使是-Wall -Wextra -pedantic
? 我是否忘记了可以告诉我该程序有问题的编译器开关?