Will this code cause a memory leak?

in ofApp.h

 unique_ptr<ofImage> myImage;

in ofApp.cpp

void ofApp::draw(){

myImage = make_unique<ofImage>();
myImage->load("image.jpg");
myImage->draw(0,0);

}

I know the memory allocation and the image loading part can be called once in setup()
But let’s say I wrote this way, will it cause any memory leak?
I learned that smart pointers don’t need to be deleted, but I also read somewhere it can be deleted using ‘reset’. http://stackoverflow.com/questions/25609457/unique-ptr-explicit-delete

When I run the code in Xcode, the memory seemed to be gradually increasing although I’m not sure if it’s a leak.
Can anyone clarify this for me please? Thanks in advance!

It shouldn’t cause a memory leak, as the myImage unique pointer is being reused, the previous ofImage generated is being deleted (when the counter reaches zero)

Try to call reset before ending the draw, and check if there is a difference in memory

1 Like

Thanks Hennio!
I just checked and there was no difference in memory usage between the two although both of them slowly increases the memory usage over time. (it starts from 23mb and grows up to 50mb in 10minutes)
Maybe this has to do with the ofImage object itself? I think some people have reported the memory leaking problem of ofImage long time ago. I hope it is fixed now.

the code is completely safe and i doubt there’s memory leaks in ofImage itself. This might be some internal optimization of the graphics card allocating more memory over time to allow for the texture to be allocated faster or something like that. in any case you can use xcode instrumets to see if there really is a memory leak. if there was please open an issue in github

1 Like

Hey Arturo.

Thank you for your clarification :slight_smile:

That is easy to check, try creating an ofMesh instead of an ofImage for
example, with a bunch of vertices (so the possible memory leak is
noticeable)