Reputation: 340
I have a very simple piece of code:
#include <iostream>
int main()
{
int *val = new int;
*val = 12;
std::cout << *val << std::endl;
delete &val;
return 0;
}
When I run Valgrind on this, I get the following error:
SUMMARY: 3 errors from 3 contexts (suppressed: 8 from 8)
1 errors in context 1 of 3:
Invalid free() / delete / delete[] / realloc()
at 0x1000ABB6D: free (vg_replace_malloc.c:533)
by 0x100000D1E: main (pointers.cpp:8)
Address 0x1048a09f0 is on thread 1's stack
in frame #1, created by main (pointers.cpp:4)
What is wrong with how I am deleting val
?
Upvotes: 0
Views: 115
Reputation: 12732
You get invalid free()
error if you try to free invalid memory.
delete &val;
here you are trying to delete address of val
, rather than the memory val
points to, which is wrong.
Try as below instead.
delete val;
Upvotes: 5