I'm a novice with valgrind, so I may do something wrong, but what am I to do if valgrind reports more frees than allocs?
Got a SSCCE here:
#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;
}
which compiles fine, and runs fine too, but valgrind says
==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.
and I'm unsure why.
Of course I can make educated guesses - obviously the offending line is where it says x = "123";
and if you comment that out, everything is good. But why then, does the compiler think this is all right, even with -Wall -Wextra -pedantic
? Did I forget a compiler switch that can tell me this program has issues?