-1

cpp newbie here

If I initiate a two pointers, like

int* a = new int(1);
int* b = new int(2);

and I want to give the pointer a a new value, shoud I delete its current value before?

In other words, what is more correct, doing

int* a = new int(1);
int* b = new int(2);
a = b;

or

int* a = new int(1);
int* b = new int(2);
delete a;
a = b;

I know I shoud use smart pointers, or NOT use them at all as a begginer, my question is more about the memory management in theory. Thanks in advance!

titoco3000
  • 51
  • 1
  • 6
  • 1
    If you don't delete it you have a memory leak. – fredrik Jul 02 '21 at 11:52
  • Yes, you need to delete a first, otherwise that memory is leaked – perivesta Jul 02 '21 at 11:53
  • What is meant above, is that after you `a=b`, you have no access to the memory previous pointed to by `a`, so now way to release it. – rawrex Jul 02 '21 at 11:54
  • Does this answer your question? [In what cases do I use malloc and/or new?](https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-and-or-new) – J... Jul 02 '21 at 11:54
  • [Should I delete a pointer?](https://stackoverflow.com/q/42545089/327083) – J... Jul 02 '21 at 11:55
  • [delete vs NULL vs free in c++](https://stackoverflow.com/q/2910587/327083) – J... Jul 02 '21 at 11:56
  • [Do I need to delete a pointer if I haven't assigned it a new value?](https://stackoverflow.com/q/13709284/327083) – J... Jul 02 '21 at 11:57
  • Thanks for the links, I tried searching it but couldnt find the correct keywords. This is the one that helped me: https://stackoverflow.com/q/13709284/327083 – titoco3000 Jul 02 '21 at 18:25

1 Answers1

2

Colloquial speech is a little misleading here. We say "delete the pointer" but more correct would be to say "delete the object pointed to by the pointer". Think of the int and the int* as two seperate entities (they really are). You can reassign to the pointer as much as you want, thats no problem for the pointer. But if you do

int* a = new int(1);  // I
int* b = new int(2);
a = b;

Then you lost any reference to the object dynamically created in I and you have no way to delete it. Its a memory leak.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • Just would like to comment for op: as far as C++ is concerned, failing to free memory is not an error: the program will yield expected results and behave correctly — that makes it different from, say, a use-after-delete. The question is, as a user of that program, is it acceptable that it slowly eats your memory because it fails to manage its resources correctly? – spectras Jul 02 '21 at 12:02