0

I have a function that returns a new array of ints, but when I call delete[] on the array, it doesn't free the memory. On my machine, the list returned by the function takes up about 0.8gb of RAM. But even after calling delete[] on the returned array, the memory is not freed, as shown by the system monitor on ubuntu. As far as I understand, delete[] is supposed to know the size of the array to free memory accordingly, so I don't understand what's going wrong.

#include <iostream>

long long int** getsquares(long long int bruh)
{
    long long int **alist = new long long int*[bruh];
    
    for (long long int i = 0; i < bruh; i++)
    {
        alist[i] = (new long long int[bruh]);
        for (long long int j = 0; j < bruh; j++)
        {
            alist[i][j] = (i * j);
        }
        
    }
    return alist;    
}

int main()
{
    const long long int count = 10000;
    long long int** list = getsquares(count);

    
    
    char bru;
    std::cin >> bru;
    

    for (long long int i = (count - 1); i >= 0; i--)
    {
        delete[] list[i];   
    }


    std::cin >> bru;
    
    return 0;
}
StealthyPanda
  • 85
  • 1
  • 4
  • In modern C++, there's no reason to use `new` or `delete`. There are better containers, like `std::vector`, `std::unique_ptr`, and `std::string`, which make `new`/`delete` unnecessary. – Eljay Apr 09 '22 at 12:46
  • The standard library provides a memory manager that controls a pool of available memory for the application. When a memory block is freed (by `delete`, `delete[]`, or `free`) it just goes back into the pool; the memory manager hangs on to it for later use. While the application is running, the OS only gets involved when the pool runs out of memory and needs to be replenished. When the application terminates all of the memory gets returned to the OS. – Pete Becker Apr 09 '22 at 13:59

0 Answers0