user8040829
user8040829

Reputation: 11

c++ - delete dynamic memory allocation from function but unable to reach the variable

I have a dynamic memory allocation of List. How can I erase this memory when the program ends?

Outside the function I do not have access to newList and if I erase it in function and delete the newList before I return, then basically I return nothing.

Is newList deleted automatically when the program terminates or do I need to manually delete it?

main.cpp:

//reverse the list, return new list 
List* reverseList(List &listToReverse) {

    //dynamic memory allocation
    List* newList = new List;

    //pointer to first node
    Node* currentPtr = listToReverse.getFirstNode(); 

    while (currentPtr != 0) {
        newList->AddElement(currentPtr->getdata());
        currentPtr = currentPtr->getNextPtr();
    }

    Node* currentNode = newList->getFirstNode();

    int size = newList->size();

    while (currentNode != 0) {
        currentNode->setId(size);
        size--;
        currentNode = currentNode->getNextPtr();
    }

    return newList;
}

int main() {

    List l1;

    cout << "The reversed list: " << endl;
    reverseList(l1)->print();    
    system("pause");
    return 0;
}

Upvotes: 0

Views: 1323

Answers (1)

nefas
nefas

Reputation: 1130

To fix you issue, you have a couple of solution:

  • store the pointer in a variable (in the main) and delete it (not the best solution)
  • return an automatic variable (not a pointer), the destructor will be called when the variable go out of scope (beware of shallow copy issues*) (check out move semantic)
  • use smart pointer

With modern OS, the memory will be cleaned after your program terminates BUT this is not a solution ! Always clean up every resources you have used !

* If you make a shallow copy and your type have (raw) pointers, the pointer inside the copy will point to the same object as the original. Which means that once the original delete his memory, the pointers in the copy will point to invalid memory.

Upvotes: 1

Related Questions