Home > database >  Deletion on a non pointer array in c
Deletion on a non pointer array in c

Time:06-11

When I have an array like this:

int* test = new int[50];
for (int i = 0; i < 50; i  )
{
    one[i] = dist4(rng);
}

(Filled with random numbers for testing)
I can free the memory like this

delete[] test;

But when I declare the array like this:

int test[50];
for (int i = 0; i < 50; i  )
{
    test[i] = dist4(rng);
}

I can't free the momory with delete or delete[].
So whats the proper way of freeing the memory here?





PS: the "dist4" function is just a random number generator:

random_device dev;
mt19937 rng(dev());
uniform_int_distribution<mt19937::result_type> dist4(1,4); // distribution in range [1, 4]

CodePudding user response:

whats the proper way of freeing the memory here?

No need to free memory explicitly using delete or delete[]in the latter case.

Assuming int test[50]; is declared inside a function, it has automatic storage duration and when test goes out of scope it will be automatically destroyed.

CodePudding user response:

The memory will automatically be freed when it does out of scope like any other non-dynamically allocated variable. This is due to automatic storage duration

CodePudding user response:

Write the code like this using a local scope:

void a_function ()
{

  // some code

  {
    int test[50];
    for (int i = 0; i < 50; i  )
    {
      test[i] = dist4(rng);
    }
  }
  // here the space for test will recovered.

  // some more code...

}
  • Related