linofex
linofex

Reputation: 340

delete position (C++)

I have a question. Reading this part of code:

int* res = NULL;
while((res = coda.Pop())!= NULL){
    std::cout << "Pop: " << *res << std::endl;
    delete res;
}

(where Pop() is a function in a class that returns a pointer to int)

I asked myself: what is the difference if I take off

delete res;

from the while cicle, as this:

int* res = NULL;
while((res = coda.Pop())!= NULL){
    std::cout << "Pop: " << *res << std::endl;  
}
delete res;

The program compile and run in both cases

Upvotes: 1

Views: 101

Answers (5)

Teivaz
Teivaz

Reputation: 5665

The coda seems to be a container and the method Pop() removes single allocated element from it. As this value was previously dynamically allocated (with new) it should be deallocated (with delete) to let OS memory manager know that this memory is free and can be reused.
In the first case you are deallocating all variables you pop from container.
The second example deallocates nothing (it will delete null pointer which is defined by standard but does nothing) and all pointers are lost. This is called a memory leak.

Though second example will work fine if you have 0 in coda but this is not the thing you would want to rely on.

Upvotes: 1

cwschmidt
cwschmidt

Reputation: 1204

coda seems to be of type stack. The stack seems to contain pointers to int that where previously allocated by new.

So, if the stack contains any number of elements where count is > 0, the elements will never be freed in the second case (the last one will not be freed, too). Because the loop runs as long as res != NULL.

In the first case, each element is taken from the stack by calling coda.Pop(), outputted and the memory is freed, by the delete statement.

If the pointers to int in the stack are just used as a reference (e.g weak-pointer, previously just assigned and not explicitly allocated by new) and the stack is not the owner of the pointers, there should not be a delete at all.

Upvotes: 0

ShuberFu
ShuberFu

Reputation: 709

My C++ is a big rusty, but the second part looks like a potential memory leak depending on what coda.PopTesta() is popping. Given that it is returning an int* it's safe to say that whatever coda.PopTesta() is allocated using a new. This means that in the second case, if your coda.popTesta() pops more than one value, all except the last value will NOT be deleted and cause memory leak.

CORRECTION: The last value will leak too. As the while look will terminate one res becomes NULL, and delete on NULL does nothing.

Upvotes: 1

Rob K
Rob K

Reputation: 8926

You leak all of the values. None of your dynamically allocated memory is freed.

Upvotes: 0

HolyBlackCat
HolyBlackCat

Reputation: 96126

In the second case you're having a memory leak because you don't delete anything. The delete after the loop tries to delete a null pointer.

Upvotes: 1

Related Questions