0

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);
}
ATK
  • 1,296
  • 10
  • 26
  • Yes, it's OK. Just remember to call `delete` on the returned pointer when you're done with it. – Adrian Mole Jul 14 '21 at 09:20
  • That's **sort of** what `malloc` does, no? – Zoso Jul 14 '21 at 09:22
  • 1
    "OK" but returning a `unique_ptr` or `shared_ptr` would make the ownership of the memory clearer and safer – Alan Birtles Jul 14 '21 at 09:23
  • It's OK, however, discouraged in modern c++. If you want to allocate memory, use `std::unique_ptr`. You might also be interested in this: [When not to allocate memory](https://stackoverflow.com/a/53898150/2466431). – JVApen Jul 14 '21 at 09:31

1 Answers1

3

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326