Is there a reason to allocate the window on the heap and not the stack?


2 Answers 2


SDL_Window win; will not compile.

SDL_Window is a so-called opaque struct. Somewhere in SDL headers, it's declared as struct SDL_Window; or something similar (without the body, as opposed to struct SDL_Window {...};). Since you don't know what members are inside, or even how large the struct is, you can't create an instance of it.

Somewhere inside of SDL sources (not in the headers accessible to you) there might be a proper definition: struct SDL_Window {...};, which allows SDL itself to create instances of this struct and access its members. But since your code doesn't see this definition, you can't do that.

(Disclaimer: I didn't actually look in the headers. SDL_Window might be typedefed to something like void *, then SDL would have to cast it to a proper struct type before accessing the members, but it's effectively the same thing.)

This accomplishes several things:

  1. You can't mess with the the members of this struct, win->foo = bar; won't compile.

    Technically you could cast the pointer to char * and read/write some bytes to it, but nothing in C/C++ can protect against that.

  2. If you link dynamically, your application is supposed to work with different versions of SDL2.dll. If SDL always handles the [de]allocation of its structs, it's able to change the size/members of the struct between versions, without your app noticing it.


Pointers to stack allocated and static memory exist, FYI. The fact that you are throwing around a pointer implies nothing about the lifetime / owner / origin of the memory you are pointing to.

This is why C++ Core Guidelines insist raw pointers are bad design and concepts such as views, ownership and smart pointers were created.

  • \$\begingroup\$ Not enough rep to post a comment on question; this does not answer the question, just an important concept I believe you're missing with that question about heap allocation. \$\endgroup\$
    – Kaldaien
    Aug 26, 2020 at 0:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .