pointer being returned from a function from an SDL library


I have been following a game engine creator tutorial on youtube which uses SDL. I have been learning many of the things involved in C++ and have been having a deeper dive involved with pointers(raw and smart) as well as learning about the stack and heap. in the tutorial there is a small function that returns a pointer. What I am not understanding is how is this pointer still available throughout the execution of the code? Here is the code in question.

SDL_Texture* TextureManager::LoadTexture(const char* texture)
  SDL_Surface* tempSurface = IMG_Load(texture);
  SDL_Texture* tex = SDL_CreateTextureFromSurface(Game::renderer, 

  return tex;

this piece of code contains the pointers information throughout...

now for learning about this material I tried creating something similar to watch how memory works with pointers from a function I created.

int* test() {
  int num = 5;
  return #

int main()
  int* ptr = nullptr;
  ptr = test();
  std::cout << "Hello World!\n";
  int testArray[5];
  int i = 1;
  testArray[0] = 1;
  testArray[1] = 2;

the pointers information gets destroyed when int i is called. Is there something that I am missing on why this isnt operating the same as the function above?

So, test() breaks this rule right here.

I unfortunately can't find enough research to my satisfaction why this is a rule, but I will post my suspicion.

num is a local variable. Local variables are allocated on the stack. The minute the function finishes execution, local variables (i.e. num) are "popped" off the stack. That is to say, they are destroyed.

Variables that are allocated via things like malloc() or the new keyword are allocated on the heap. The heap isn't destroyed during the execution of the program

The address stored in num in a case such as this:

int *num = new int(37);

is an address on the heap. It is perfectly valid even after the function finishes execution. Thus, you can use it after the function finishes.

SDL '97: Time for Testing: SDL, MSC and Trends, The function CString2CStar converts the SDL charstrings to C char pointers with a pointer to the start of the array of structs to be searched, and the integer key to search for. findelement is translated to SDL as a value returning procedure​, and if an Another example is the fprintf function that of the standard C library, which  So while std::unique_ptr<SDL_Surface, SurfaceDeleter> and std::unique_ptr<SDL_Surface, void(*)(SDL_Surface*)> solve the same problem in a similar way, the former type is still only the size of a pointer while the latter type has to hold two pointers: both the SDL_Surface* and the function pointer! When having free function custom deleters, it

In your test function, num is a local variable. It is destroyed by the end of test().

You need to allocate an integer in test to make it work. In this case, the ownership of the pointer is transferred to you: you need to delete it.

int* test() {
  int* num = new int(5);
  return num;

int main() {
  int* ptr = test();
  std::unique_ptr<int> int_deleter(ptr);
  std::cout << "Hello World!\n" << *ptr;

Another example of returning a pointer is returning a class member. In this case, refer to the documentation on whether you're transferred the ownership. For example:

class A {
  A() : num(new int(5)) {}
  virtual ~A () { delete num; }

  // `A` keeps the ownership of the pointer.
  const int* GetNum() const { return num; }

  int* num;

int main() {
  A a;
  std::cout << *a.GetNum() << std::endl;

Returning to the SDL_CreateTextureFromSurface example, it is likely that a new variable is allocated in the method. You need to refer to the documentation about the ownership of the returned pointer (whether you or the library deletes the pointer).

Game Engine Design and Implementation, calling SDL_Init to initialize the graphics rendering • components of the SDL library. Next, the init method calls the SDL function SDL_SetVideoMode to initialize A valid pointer to this window is returned in the variable m_RenderWindow if diagnostic information relating to the video hardware being used to power the  EDIT 2 Look at lines 110 and 113 in your code (pastebin). You create moving, then you set moving = shot, then you free moving on line 121. You never used malloc() or calloc() on it in that translation block.

SDL_LoadFunction, void* SDL_LoadFunction(void* handle, const char* name) Returns a pointer to the function or NULL if there was an error; call SDL_GetError() for pointers with the same calling convention as the actual library function. * Hide a pointer to the managed struct before the actual pixel data. * This allows the caller to only have to worry about the data they * want, while still allowing this library to perform more complicated

There are 4 basic storage classes in C/C++:

  1. Automatic: Local Objects - normally created on stack - get destructed once the scope they reside reaches its end. The scope normally resides in a function body, therefore all automatic objects constructed within a function are already destructed when the function returns; this includes function argumemts too.
  2. Internal/static: Their lifespan is longer than most automatic variables. Once constructed, they live until program finishing point is reached; when they are automatically destructed. These objects are only visible/accessible in the nesting module(translation unit)/function/scope.
  3. Global/external: These objects live longer than all objects in the 1st 2 classes above. They are constructed once the program starts and destroyed right before the program ends when all automatic and internal objects are already dead.
  4. Dynamic/heap: They have flexible lifespan. They can be constructed anytime during program execution and destroyed anytime after. They normally need manual disposal unless proper smart pointers are used to automate management of their lifespan. One common source of bugs is to not dispose of them properly.

So normally, returning a refrence/pointer to any none-automatic objects is ok.

Programming Linux Games, SDL provides a convenient SDLLoadWAV function, but it is of little use to A better option is the libsndfile library maintained by Erik de Castro Lopo, This function accepts a filename and a pointer to an SFINFO structure and returns a pointer  SDL_CreateWindow is called and the result is immediately passed to the unique_ptr as the first parameter and a function pointer to SDL_DestroyWindow is passed as the second. At this point the SDL_Window resource is now owned by the unique_ptr instance and when it goes out of scope, or is otherwise destroyed, SDL_DestroyWindow will be called.

C++14 and SDL2: Managing Resources, Like most C libraries that provide access to resources, the SDL2 deleter, a void function taking a pointer to an SDL_Window instance, This ensures that any resource returned by make_resource is guaranteed to be valid. SDL has a function to get the name of the joysticks as assigned by the operations system and that function is SDL_JoystickName. The joystick is specified by an index where 0 is the first joystick and the last joystick is the number returned by SDL_NumJoysticks - 1. In the demonstration a list of all available joysticks is printed to stdout.

Understanding Pointers In Respect to SDL, SDL uses a lot of pointers because it's a C library and doesn't have clever we would not use & when passing occur to the function but then there No. There are three ways to pass and return. 1)Value/Copy 2)Pointer 3)Reference Pretty much think of parameters as local variables being constructed and  unit SDL2;: SDL2.pas v1.0 29/07/2013 first version for DelphiXE: v1.1 27/08/2013 add MACOS compability: v1.2 31/05/2014 delete sdl2.inc: Simple DirectMedia Layer

WIN04-C. Consider encrypting function pointers, If an attacker can overwrite memory containing function pointers, they may be able The Microsoft SDL [Microsoft 2012] recommends encoding long-lived pointers in your code. Note that DecodePointer() does not return success or failure. to encrypt/decrypt pointers instead without the addition of these library calls so it  The file extensions are informational, and only required as a hint to choosing the correct decoder, since the sound data may not be coming from a file at all, thanks to the abstraction that an SDL_RWops provides. The returned value is an array of pointers to Sound_DecoderInfo structures, with a NULL entry to signify the end of the list:

  • You are returning the address of a temporary variable. Once that function returns, there is no num anymore.
  • so does the function SDL_CreateTextureFromSurface essentially create a variable in heap, and return the pointer to said variable?
  • Look again. Where does that num variable come from? It isn't from the heap -- it is a local variable that goes poof into the night when the function returns.
  • let me try to rephrase my question, so i was trying to understand how tex isnt destroyed. so i tried to mimic the implementation in my own code, so does SDL_CreateTextureFromSurface essentially create a variable in heap, and return the pointer to said variable? (i should probably edit out my 2nd block of text so my question is more precise)
  • You didn't mimic the implementation -- that's the point. You thought you did, but you didn't. If you were to mimic it, you would have created a function that returned a pointer to a dynamically allocated entity.
  • Minor detail: are allocated on the heap -> are allocated in dynamic memory. Dynamic memory almost always in a heap, but C++ is a very big umbrella and leaves the actual implementation details to the implementer. Technically the fluffy white blood of Care Bears could be used for dynamic storage.
  • Do I need to update my answer? If so, what do you suggest?
  • Keep the answer as simple as possible. Practically no one sees anything but stacks and heaps. That said, something like Local variables are allocated in Automatic storage, usually a stack. and ...the new keyword are allocated in Dynamic storage, usually the heap. is correct in both ways.
  • The heap isn't destroyed during the execution of the program Could use some rewording, but I don't think that, even if reworded, it can add anything not covered by the example that follows.
  • that makes great sense, im more of trying to understand why tex isnt destroyed though? so does the function SDL_CreateTextureFromSurface essentially create a variable in heap, and return the pointer to said variable?
  • There are two elements here: the pointer tex and the SDL_Texture object tex points too. The tex pointer is destroyed by the end of your function, but the object it points to is not because it's allocated on heap.
  • It is not destroyed because anything dynamically allocated must be explicitly destroyed by some "deleter" function, whether it is delete, delete[], free(), GlobalFree (from Windows), etc.
  • @twokdavey read the documentation for SDL_CreateTextureFromSurface. You do not know what SDL did to allocate storage for that pointer so you cannot safely dispose of it until you know how to dispose of it. Once you do know how to dispose of the texture, you can call the function (hint: SDL_DestroyTexture) or wrap the call in a custom deleter for std::unique_ptr to automate the clean-up for you.
  • In fact you could overload new and delete to do exactly what Hanjoung Lee says. However, I am at a loss as to how you would pass in the parameters needed by SDL_CreateTextureFromSurface.