-3

I have a function that creates a new node and places it in its correct place in a list linked by pointers. However I ran a test and printed the address of each node when I create it and noticed it is the same. I am not calling delete and I am using new so I was wondering where my memory is being deleted. I am calling new on "Node". This code is in the method of a class that is not the Node class, but is in the same .h file.

calling new:

image

memory locations:

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jake Sak
  • 40
  • 7
  • 1
    All questions on stackoverflow.com must include all pertinent information ***in the question itself as plain text***. Dodgy links to shady external web sites can stop working at any time, rendering the question meaningless. You need to [edit] your question and follow the instructions in stackoverflow.com's [help] for creating a [mcve]. Otherwise this question will closed as off-topic, and deleted. – Sam Varshavchik Dec 05 '18 at 02:39
  • `A a = *(new A)` is a memory leak, and `a` won't be the same object created by `new` – kmdreko Dec 05 '18 at 02:39
  • 1
    When you do `Node N = *(new Node(Key, Val))`, the *value* is copied to `N` and the *pointer* is leaked. And since `N` is on the stack the pointer to that location can end up being the same from one run to another. You are essentially looking at the wrong location. – Pavan Yalamanchili Dec 05 '18 at 02:47
  • The answers here might be useful for understanding `new` and pointers: https://stackoverflow.com/questions/655065/when-should-i-use-the-new-keyword-in-c?rq=1 – Pavan Yalamanchili Dec 05 '18 at 02:50
  • @Kevin oops, thanks fixed. – Pavan Yalamanchili Dec 05 '18 at 03:07

1 Answers1

1

In the code you showed, N is a local variable that is created and destroyed each time you enter and leave the block. It is not surprising that it always has the same address. Your code is no different from this:

for (int i = 0; i < 10; ++i)
{
    int j = i;
    cout << "Value: " << j << " Location: " << &j << endl;
}

Each iteration of the loop creates a new instance of j at the beginning and destroys that new instance at the end. Even though each j has a different value, they can all live at the same address because have non-overlapping lifetimes. You can see that what value you store in j doesn't matter. So this will likely also show different values but the same location.

Your use of new is irrelevant because you don't save the value it gives you. You dereference it and throw it away.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278