Deletion on a non pointer array in c++

Viewed 110

When I have an array like this:

int* test = new int[50];
for (int i = 0; i < 50; i++)
{
    test[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 memory with delete or delete[].

What's the proper way of freeing the memory here?

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]
3 Answers

What's 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.

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

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