Problem clearing dynamically allocated memory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int *foo() 
{
    int *ptr = new int[3];
    return ptr; 
}

int main(){

int *array = foo();

array[0] = 3;
array[1] = 6;
array[2] = 14;

cout << *array << " " << array[1] << " " <<array[2];

delete [] array;

cout << endl << *array << " " << *(array+1) << " " << array[2];

cin.get();
}


Line in bold outputs 3754990 3759056 (or similar) and 14. The value of array[2] remains.Any ideas?
Array isn't dynamically allocated yet you're trying to delete it.

You need to do a for loop to delete the content in array.

1
2
for(int i = 0; i < sizeof array/sizeof array[0]; i++)
delete array[i];



edit: Ignore this I got confused with object allocation.
Last edited on
I am fairly sure that an array created like that int* arr = new int[3] is dynamically allocated.

(An array like this int arr[3]; isn't.)

I also think that delete [] arr is the correct way to deallocate an array.
EDIT: lordmat, I may be wrong, but I'm not sure your loop will work. array[i] is an element of the array, i.e. an integer and not a pointer so you cannot delete it. Also, when I tried delete &array[0] this resulted in an error.

genesys, I copied and pasted your code into Visual Studio 2010 and it ran fine. All three array values after deletion were random values.

Hope this helps.
Last edited on
What do you mean by "clearing" the array? delete doesn't set memory to any value, just releases it for reallocation.Maybe the values will change quickly, maybe they will hang around for ages. There's no promise made about what happens to the memory, only that you can't trust it not to have changed (hence the recommendation against reading for memory that you have deleted, although you sometimes see people doing it anyway).
Last edited on
That is what i meant - release used memory to prevent memory leak.

I just wanted to return a pointer to an array from the function and then release memory and see if this worked

P.S Thanks for the comments.
Last edited on
Moschops, in that case, what causes the change of values in this program? When I tried this, I didn't declare any other variables, so what changes the memory in the mean time? Is it cout? Or could it be something outside our program which reused the memory?
Last edited on
Topic archived. No new replies allowed.