1

I want to free up the memory of the array of pointers of type structNode.

struct structNode
{
    int value;
}
typedef structNode * Node;

int main()
{
    Node ListNodes[1000];

    //Fill and Clear the array 100 times.
    for(int j=0; j<100; j++)
    {
        //Add a pointers to the array
        for(int i = 0; i < 1000; i++)
        {
            Node newNode = new structNode;
            newNode->value = 3;
            ListNodes[i] = newNode;         
        }

        // Deleting each pointer
        for(int i = 0; i < 1000; i++)
        {
            delete ListNodes[i]; 
        }
        // delete the array
        delete [] ListNodes;
    }
    return 0;
}

Is this the correct way to clear the memory in each cicle? I am asking this question because I watch the program when it runs with a task manager, and it only increments the memory usage instead of keeping the memory usage at a constant range.

dragosht
  • 3,237
  • 2
  • 23
  • 32
Mauricio
  • 433
  • 5
  • 15

2 Answers2

4

Generally you cannot reclaim memory allocated for automatic variables on the stack until the allocating function exits, so only the pointers contained in the static array can have delete called on them. Since main does not exit until the completion of the lifetime of the program, the lifetime of the memory footprint that ListNodes utilizes will match the lifetime of the program.

Also using the host OS task manager to check for overall memory usage is not a good tool, as the host OS may still claim memory for your application after you've called delete on heap storage in order to avoid having to constantly go to the host OS for additional heap storage memory allocations. Going to the host OS for memory allocation is expensive...

Jason
  • 31,834
  • 7
  • 59
  • 78
3

No, the array is on the stack and you can't free it with a delete:

delete [] ListNodes;

Freeing memory not allocated (or freeing a different object in that place) is undefined behavior.

There's no need to delete that memory and you can't (without horrible low-level hacks) delete stack memory. If that proves to be a problem reduce the amount of stack-allocated memory and opt for a dynamic allocation.

I suggest reading the differences between heap and stack here.

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246