1

If I have a global pointer, and I initialize it like this:

Image *fbPtr = NULL;
...
void initFrameBuffer(const BootInfo::FrameBuffer &info) {
    Image fb(info.getWidth(), info.getHeight(), info.getBpp(), info.getBuf());
    fbPtr = &fb;
}

Would it be undefined behaviour? Would the fb variable be deleted by the end of the function and the pointer be rendered invalid? I'm using GCC10 and compiling with -std=c++2a, if it makes any difference.

1 Answers1

1

Yes, this is undefined behavior, specifically the use of a pointer to a variable on the stack (variables defined without the new keyword) is called a dangling pointer. In this case you can simply replace the function body with this:

void initFrameBuffer(const BootInfo::FrameBuffer &info) {
    Image * fb = new Image(info.getWidth(), info.getHeight(), info.getBpp(), info.getBuf());
    fbPtr = fb;
}

This defines image as a pointer and allocates the data on the heap instead of the stack. This also means that you need to eventually delete it with delete fbPtr;, or else the image object will remain taking up memory forever. If you change the fbPtr variable without deleting the contents, this will cause a memory leek, meaning your program is repeatedly allocating more memory without ever deallocating it, meaning eventually you will run out of memory.

BEN1JEN
  • 71
  • 1
  • 7