p_img1
and p_img2
being IplImage*
previously cvLoad'ed, I would like p_img1
to become a copy of p_img2
.
Writing *p_img1 = *p_img2;
seems to work fine (I can check it in debug mode, as well as by displaying images), except that after that line, using cvReleaseImage
for one pointer will apparently also destroy the other one. I don't understand it as the two pointers (the two addresses) are different, only the fields of the structures are copied.
I noticed that using p_img1 = cvCloneImage(p_img2);
fixes the problem.
Could somebody please explain why *p_img1 = *p_img2
is wrong ? What cvCloneImage()
does differently ?
I would suggest you to have some further reading on C++ pointer related references.
Your p_img1
and p_img2
are pointers to IplImage structure.
p_img1
pointing to imageheader1p_img2
pointing to imageheader2however, the IplImage
structure does not contain the image data, instead it holds the pointer to memory location storing the pixel value.
Executing *p_img1 = *p_img2
, will make the content of p_img1
similar to p_img2
, thus
pixeldata1 will be unreferenced and become potential memory leak if it is not released. When releasing, cvReleaseImage
takes parameter of 'pointer of pointer', which actually releases the imageheader pointed, so both imageheader1 and imageheader2 will point to invalid memory.
cvCloneImage
has built-in memory allocation, where it actually allocate new block of memory before copying the content into it. Executing p_img1 = cvCloneImage(p_img2)
will cause OpenCV to allocate new memory block (pixeldata3), copying data from pixeldata2 (pointed by imageheader2 of p_img2
) and then update the imageheader1 (pointed by p_img1
).
=> pixeldata1 will be unreferenced and become potential memory leak if it is not released.