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

**URL:** <https://discourse.processing.org/t/proper-buffer-memory-management-for-pimage-created-inside-a-function-and-used-outside-it/43616>\
**Category:** Beginners\
**Created:** [January 4, 2024, 12:04pm UTC](https://discourse.processing.org/t/proper-buffer-memory-management-for-pimage-created-inside-a-function-and-used-outside-it/43616 "2024-01-04T12:04:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MuddyGardener](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/muddygardener/32/1719_2.png) [@MuddyGardener](https://discourse.processing.org/u/MuddyGardener)\
**Post date:** [January 4, 2024, 12:04pm UTC](https://discourse.processing.org/t/proper-buffer-memory-management-for-pimage-created-inside-a-function-and-used-outside-it/43616/1 "2024-01-04T12:04:06Z")

</div>

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!

```auto
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;
}
  

```

---

<div class="post-metadata">

**Author:** ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)\
**Post date:** [January 4, 2024, 4:08pm UTC](https://discourse.processing.org/t/proper-buffer-memory-management-for-pimage-created-inside-a-function-and-used-outside-it/43616/2 "2024-01-04T16:08:06Z")

</div>

> [@MuddyGardener](#):
>
> This code works, as you can see, but I’m not sure if it SHOULD work.

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

> [@MuddyGardener](#):
>
> 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,

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`.
