Say that I want to allocate an array of ints.
int* array = new int[5];
and then later on assume I have 5 int pointers, all pointing to the 5 different integers of the array.
int* v1 = &array[0];
int* v2 = &array[1]; //etc..etc
Now that I have "remembered" the location of all the ints in the array, I would like to manage the elements as individual integers. So in theory if I then set my array pointer to NULL...
array = NULL;
I would in theory not have to worry, because all my v1 and v2 pointers are pointing to all the elements in the array. The problem then is say like I am done with v2. So I would like to delete v2 to free up those 4 bytes.
delete v2;
Unfortunately, when I try to do that, bad things happen. I assume because the memory allocation table says "Hey, you can't delete in that space because it currently belongs to part of an int array!"
So thats fine, I would then like to say
delete [] array;
but if I do that, I want to make sure that when I do...
int* v1 = new int;
I want to guarantee that the newly allocated integer was created at the address of array[0]. So is there a way to specify where a new value is created? Or can I somehow control the memory list?
I've attempted to use the placement operator by calling something like...
int* v1 = new((void*)&array[0]) int;
but then when I delete the array with the delete operator and then attempt to access v1 by dereferenceing it... say
cout<<*v1;
I get a bunch of text to the screen that says "double free or corruption (fasttop): ...
I am using Ubuntu 11.04 and g++ compiler in codeblocks.
Also, just FYI, I have looked at Create new C++ object at specific memory address? and that is where I got the information about the placement operator, but it appears to not be working the way I need it to work.
#include <iostream>
using namespace std;
int main()
{
int *array = new int[20];
for(int i=0;i<4;i++)
{
array[i] = i;
}
int* a = new ((void*)&array[0]) int;
int* b = new ((void*)&array[1]) int;
int* c = new ((void*)&array[2]) int;
int* d = new ((void*)&array[3]) int;
int* e = new ((void*)&array[4]) int;
cout<<*a<<endl;
cout.flush();
delete[] array;
cout<<*a;
delete a;
delete b;
delete c;
delete d;
delete e;
return 0;
}