Memory corruption error when using auto_ptr
I wrote a sample code to examine how auto_ptr works, but when I run my example code, I get memory corruption.
My sample code is below.
#include <iostream>
#include <memory>
#include <cv.h>
#include <highgui.h>
using namespace std;
int main()
{
for (int i = 0; i < 1000; i++)
{
IplImage* temp = cvLoadImage("sample.png");
auto_ptr<IplImage> aptr (temp);
}
}
Below is the error message I received from the above program:
*** glibc detected *** ./a.out: double free or corruption (out): 0x00000000008325c0 ***
======= Backtrace: =========
/lib64/libc.so.6[0x36eb276166]
/lib64/libc.so.6[0x36eb278ca3]
./a.out[0x400e9b]
./a.out[0x400df7]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x36eb21ed1d]
./a.out[0x400cf9]
======= Memory map: ========
00400000-00402000 r-xp 00000000 00:19 7879127
Can anyone explain the reason for the error above?
source to share
See the comments on the answer karlphillip , I'm going to update this answer to use cvReleaseImage
.
It should be noted that you can do this with unique_ptr
because it will allow you to specify a custom deleter:
unique_ptr<IplImage, void(*)(IplImage*)> aptr(cvLoadImage("sample.png"), [](IplImage* temp){cvReleaseImage(&temp);});
This will allow you to use the automatic pointer without modifying it cvLoadImage
and still cleanly delete memory.
EDIT:
unique_ptr
is a native pointer, which means it will perform a delete to clear the memory allocated to it: https://en.cppreference.com/w/cpp/memory/unique_ptr.
Unlike auto_ptr
, which is always called delete
, you can pass a custom Deleter to unique_ptr
.
When passing a custom Deleter to, unique_ptr
you need to provide a functor signature to unique_ptr
.
So, to break my code:
-
unique_ptr<IplImage, void(*)(IplImage*)>
: Thisunique_ptr
which will containIplImage*
. The remover returnsvoid
and acceptsIplImage*
as an argument. -
aptr(cvLoadImage("sample.png"),
: This argument must be a managed pointer whichunique_ptr
will take responsibility, ornullptr
Obviously.cvLoadImage
returns to the managed pointer. -
[](IplImage* temp){cvReleaseImage(&temp);});
This is a custom Deleter that I transfer tounique_ptr
. I wrap it in a lambda so that I can dereference the managed pointer contained inunique_ptr
because, according to thiscvReleaseImage
, the pointer to the link to be deleted needs to be obtained.
source to share