Sign in to follow this  
M-374 LX

Static or dynamic object allocation?

Recommended Posts

I suppose it is better to use static memory allocation when one needs a fixed number of elements of a certain object. If so, why are most objects in SDL (including objects of the type SDL_Surface) and Allegro typically declared as pointers and allocated dynamically by functions like SDL_CreateRGBSurface()?

Share this post


Link to post
Share on other sites

The total size of a SDL_Surface in a 32-bit system, as seen in the SDL wiki, is likely to be 60 bytes. Each pointer itself (not the data it points to) occupies 4 bytes, correct? So, is the object's size really not known at compile time?

 

In case you actually refer to the total size of the data pointed by the pointers within the SDL_Surface, why should the SDL_Surface object itself be allocated dynamically?

Share this post


Link to post
Share on other sites

Note that one of the SDL_Surface members is a ref count. It's expected that you can extend it's lifetime by incrementing the ref count, which is hard to do if someone's allocated it on the stack. 

Share this post


Link to post
Share on other sites

The total size of a SDL_Surface in a 32-bit system, as seen in the SDL wiki, is likely to be 60 bytes. Each pointer itself (not the data it points to) occupies 4 bytes, correct? So, is the object's size really not known at compile time?


SDL is meant to be used as a dynamic library. They are free to add new members because of this at any time should they wish. Were it static, you'd be forced to use SDL as a static library. Among other problems, this would make it difficult or impossible to have SDL updates automatically copy with platform changes that otherwise don't require a recompilation of your application (e.g. the transition from X11 to Wayland on many Linux systems).

In case you actually refer to the total size of the data pointed by the pointers within the SDL_Surface


Never do that. There is absolutely no good reason to ever do it. If you think you're being especially clever and optimizing somehow by doing it, you're being _too_ clever and should knock it off.


In any case, you're worrying about something you don't need to worry about. If and when you find that SDL's treatment of allocation is in any way a bottleneck or performance dog then file a bug report against SDL with the proof. It's unlikely you'll have any test case like this that isn't just a result of something silly in your code (e.g., if you're allocating/deallocating surfaces during your game loop; don't do that).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this