Proper buffer memory management for PImage created inside a function, and used outside it

This code works, as you can see, but I’m not sure if it SHOULD work. I am reserving the buffer space for the Test Pimage inside a function, and returning the values that have been set inside the function.

I have a weird kind of unease that the memory created for the PImage inside the function will be freed up when the function exits, and if it’s working now, it’s working accidentally because it hasn’t stepped on its own shoelaces, but at scale this will result in untold horrors.

Can I rely on this working, in general?

thanks!

PImage Test;

void setup() {
  size(200, 200);
  background(255);
  Test = ImageFunction();
  image(Test, 0, 0);
}

PImage ImageFunction(){
  PImage InteriorTest = createImage(100, 100, RGB);
  for (int i = 1; i < InteriorTest.pixels.length; i++) {
    InteriorTest.pixels[i] = 0;
  }
  return InteriorTest;
}
  

Yes it should work because there is nothing wrong with your code :smile:

Inside the function you have a local variable called InteriorTest but this is not the actual image rather an object reference to an image object. The function returns this reference which is then stored in Test.

Although the variable InteriorTest no longer exists the memory for image object will not be released because we have another reference to it i.e. Test.

4 Likes