using linux/glibc? Segfault because you damaged the link list
所在版块:求学狮城 发贴时间:2005-10-30 06:28  评分:

用户信息
复制本帖HTML代码
高亮: 今天贴 X 昨天贴 X 前天贴 X 
of freed memory chunks.

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

.
欢迎来到华新中文网,踊跃发帖是支持我们的最好方法!

 相关帖子 我要回复↙ ↗回到正文
why does not "g++ -Wall" give warning message when compiling the following code? icky   (660 bytes , 928reads )
delete array; not delete [] array; simon   (470 bytes , 640reads )
do u mean icky   (132 bytes , 387reads )
no la...as simon said, object vs primitive data type sarah   (0 bytes , 390reads )
。。。。。。ok... simon   (0 bytes , 287reads )
different btw 'object' and 'primitive data type' simon   (0 bytes , 342reads )
using linux/glibc? Segfault because you damaged the link list hash   (1304 bytes , 644reads )
a mistake hash   (233 bytes , 409reads )
but after icky   (103 bytes , 385reads )
The default libstdc++ operator new and delete use the libc malloc and free. hash   (86 bytes , 463reads )