Valgrind reports more frees than allocs

I'm new to valgrind, so I can do something wrong, but what should I do if valgrind reports more frees than allocs?

There is 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 works fine, 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 not sure why. Of course, I can make reasonable guesses - it is obvious that the offensive line is where she says x = "123";, and if you comment on this, everything will be fine. But why then does the compiler think that everything is in order, even with -Wall -Wextra -pedantic? Have I forgot about the compiler, which can say that this program has problems?

+3
source share
3 answers

.
, .

x = "123";

, , , .

+1

x = "123" x = something("123"), . something , x, delete [] - .

, / .

+1

Your class somethingcontains a raw pointer that is incorrectly controlled by its copy constructor and assignment (compiler). Do not use raw pointers, or, if necessary, more carefully define class methods. But don't really use source pointers.

0
source

All Articles