why does not "g++ -Wall" give warning message when compiling the following code?
登录 | 论坛导航 -> 华新鲜事 -> 求学狮城 | 本帖共有 10 楼,当前显示第 2 楼 : 从楼主开始阅读 : 本帖树形列表 : 返回上一页
作者:hash (等级:7 - 出类拔萃,发帖:5077) 发表:2005-10-30 06:28:53  2楼  评分: 
using linux/glibc? Segfault because you damaged the link list
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

欢迎来到华新中文网,踊跃发帖是支持我们的最好方法!原文 / 传统版 / WAP版只看此人从这里展开收起列表

本帖共有 10 楼,当前显示第 2 楼,本文还有 N-1 层楼,要不你试试看:点击此处阅读更多 >>



请登录后回复:帐号   密码