dynamic array deletion

I'm having trouble deleting a dynamic array and am getting a glibc detected error message. Code is as follows:

#include <iostream>

using namespace std;

int main () {
const int NO_OF_ARRAYS = 5;
const int ELEMENTS_PER_ARRAY = 3;
int i, j;
int *mem_alloc = new int[NO_OF_ARRAYS * ELEMENTS_PER_ARRAY]; //allocate memory for 15 ints
int **pointers = new int*[NO_OF_ARRAYS]; //allocate an array of 5 pointers for 5 int arrays

/* assign each element of pointers every third memory address from mem_alloc */
for ( i = 0; i < NO_OF_ARRAYS; i++ ) {
pointers[i] = &mem_alloc[i * ELEMENTS_PER_ARRAY];
}

/* to test funcionality give each element of mem_alloc a value */
for ( i = 0; i < NO_OF_ARRAYS * ELEMENTS_PER_ARRAY; i++ ) {
mem_alloc[i] = i;
}

/* Then access the values through pointers as per a multidimensional array */
for ( i = 0; i < NO_OF_ARRAYS; i++ ) {
for ( j = 0; j < ELEMENTS_PER_ARRAY; j++ ) {
cout << "test: " << pointers[i][j] << endl;
}
}

/* delete allocated memory */
for ( i = 0; i < NO_OF_ARRAYS; i++ ) {
delete pointers[i];
}
delete pointers;
delete mem_alloc;

return 0;
}


any assistance greatly appreciated
If you allocate with new[], you must deallocate with delete[].

1
2
3
int *mem_alloc = new int[NO_OF_ARRAYS * ELEMENTS_PER_ARRAY];
...
delete mem_alloc;


1
2
3
int **pointers = new int*[NO_OF_ARRAYS];
...
delete pointers;


This
delete pointers[i];
doesn't seem to have a corresponding new at all.
Last edited on
Topic archived. No new replies allowed.