Search code examples
c++new-operator

Is it Okay to do new inside a function and return the pointer to it?


Is the following code snippet correct, or what could be wrong with it?

As I know, memory allocated with new, will not be erased unless there is a delete so returning its pointer should be fine?

// Example program
#include <iostream>
#include <string>

int* a()
{
    int* aa = new int(1);
    *aa = 44;
    return aa;
}

int main()
{
  int *aa = a(); 
  
  printf("%d ", *aa);
}

Solution

  • It's not ideal. Who is responsible for deleting the pointer? You don't delete it anywhere in the example, so there is a memory leak.

    Typically, if you need dynamic allocation, then you should return a smart pointer instead. That said, its usually also best to avoid unnecessary dynamic allocation. There's probably never a need to dynamically allocate a single int.