I try to clean the memory to delete pointers. But the last instruction (delete array[i]) generate this error : pointeurs-tableau(14994,0x110a67600) malloc: *** error for object 0x7ff7bb760760: pointer being freed was not allocated
But I dont know why.
`
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
int main()
{
default_random_engine gen(time(0));
uniform_int_distribution<> dis(1, 100);
const int max = 20;
int* array[max];
// un tableau normal
int val[max];
for (int i = 0; i < max; i ) {
val[i] = dis(gen);
}
for (int i = 0; i < max; i )
{
array[i] = &val[i];
}
//... modifying function on the array
// show the array
for (int i = 0; i < max; i ) {
cout << val[i] << " ";
}
// deleting pointeurs (problematic !!!!)
for (int i = 0; i < max; i )
{ delete array[i];}
delete[] array;
return 0;
}
`
Could you help me please ?
CodePudding user response:
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.
CodePudding user response:
Thank you for your answers. then i did some modification to create my array of pointer like this
int **array = new int*[max];
for(int i=0;i<max;i ){
array[i]= new int;
}
but in the end, the delete makes the same error.