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?

+3


source to share


2 answers


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*)>

    : This unique_ptr

    which will contain IplImage*

    . The remover returns void

    and accepts IplImage*

    as an argument.
  • aptr(cvLoadImage("sample.png"),

    : This argument must be a managed pointer which unique_ptr

    will take responsibility, or nullptr

    Obviously. cvLoadImage

    returns to the managed pointer.
  • [](IplImage* temp){cvReleaseImage(&temp);});

    This is a custom Deleter that I transfer to unique_ptr

    . I wrap it in a lambda so that I can dereference the managed pointer contained in unique_ptr

    because, according to this cvReleaseImage

    , the pointer to the link to be deleted needs to be obtained.
+4


source


IplImage*

allocated through cvLoadImage()

must be released using cvReleaseImage()

.

cvLoadImage()

uses malloc()

and cvReleaseImage()

uses free()

to do the job, but auto_ptr

uses delete

(which is in C ++).



You just can't mix malloc()

with delete

.

+5


source







All Articles