delete operator must be used only on a dynamically allocated memory (with the new).
In your case you have an array int val[max];
with automatic storage duration. And array of pointers int* array[max];
also with automatic storage duration.
Automatic storage duration means memory for arrays int val[max];
and int* array[max];
will be allocated when execution enter in the scope they declared and will be freed when execution lives the scope (at your case main function).
But when you trying to call delete array[i];
you force compiler to attempt clear element from int val[max]
onto which array[i]
pointing to. But it can't do that because this value never have been allocated on the heap with new.
// Edit
As you mentioned in comment to this answer you added changes to your code:
int **array = new int*[max];
for (int i=0; i < max; i++) {
array[i] = new int;
}
An still have the same error;
The reason behind it most likely is that you still have this cycle
for (int i = 0; i < max; i++) {
array[i] = &val[i];
}
int** array;
item: array[i]
- is a pointer.
You allocated memory on the heap and stored address of this memory into that pointer:
array[i] = new int;
Lets say new int;
returned address ADDRESS_FROM_HEAP
Then you took address of int val[max];
by &val[i]
and assigned it to the pointer array[i] = &val[i];
Lets say &val[i]
equal to ADDRESS_FROM_STACK
Then you trying to delete array[i];
But at this moment array[i] == ADDRESS_FROM_STACK
;
Not only delete unable to free memory on ADDRESS_FROM_STACK, you also lost ADDRESS_FROM_HEAP and memory by this address will not be freed.
If you would change your loop to this
for (int i = 0; i < max; i++) {
*array[i] = val[i];
}
You will store a COPY of val[i]
in the memory pointed by array[i]
pointer.
But by looking at your code I can't honestly see why you allocate any memory dynamicly.
If you will just leave code as it is in your original question and just remove all delete
statements, it will work just fine.