bype 0-8 of a freed memory chunk contains pointers to the previous/next freed chunks. in
for (int i = 0; i < 8; i ++)
flag[i] = true;
you destroyed the link list. When you try to free the next chunk (darray), free() tries to merge the two adjacent freed chunks. As the link list is corrupted, you see a segfault.
There are two ways to avoid segfault with you wrong program:
1.
#include <iostream>
using namespace std;
int main ()
{
bool * flag = new bool[16];
delete [] flag;
double * darray = new double[10];
for (int i = 0; i < 8; i ++)
flag[8+i] = true;
cout << "before releasing darray" << endl;
delete [] darray;
cout << "darray released" << endl;
return 0;
}
In this case, you didn't touch the first 8bytes, so you don't get a segfault.
2.
#include <iostream>
using namespace std;
int main ()
{
bool * flag = new bool[8];
delete [] flag;
double * darray = new double[1];
for (int i = 0; i < 8; i ++)
flag[i] = true;
cout << "before releasing darray" << endl;
delete [] darray;
cout << "darray released" << endl;
return 0;
}
In this case, size of darray chunk is too small, free() choose not to merger the two chunks. No segfault, for the moment.
tested on gcc4/glibc2.3
for more details, take a look at this article: http://www.phrack.org/show.php?p=57&a=9