69,373
社区成员
发帖
与我相关
我的任务
分享
//这段代码把二叉树的顺序储存转化为链式储存,参数*list是形如:ABCD#ED的串,#表示NULL
//在这段代码的最后,free(queue) 导致了堆损坏,分析了一下,觉得不会出错。。。在调试的时候,没有出错,直接运行程序,就直接出错了,求解释
node * listTolink( node *list )
{
node *root = NULL;
node *p = NULL ;
node **queue = NULL;
int x = 0 ;
int rear = 0 ;
int i ;
queue = (node **)malloc(sizeof(node * ) * list[0].data) ;
root = (node *)malloc(sizeof(node));
queue[0] = root ;
*root = list[1];
for( i = 2; i < list[0].data; i++,x++)
{
if ( list[i].data != '#' )
{
p = (node *)malloc(sizeof(node));
*p = list[i] ;
queue[x]->lchild = p ;
queue[++rear] = p ;
}
else
queue[x]->lchild = NULL ;
i++ ; // 判断右孩子
if ( list[i].data != '#' )
{
p = (node *)malloc(sizeof(node));
*p = list[i] ;
queue[x]->rchild = p ;
queue[++rear] = p ;
}
else
queue[x]->rchild = NULL ;
}
free(queue) ;
return root ;
}
#include <time.h>
#include <stdlib.h>
#include <windows.h>
int main() {
int a,b[11];//本来是b[10],为判断哪句越界,故意声明为b[11]
srand((unsigned int)time(NULL));//按两次F11,等黄色右箭头指向本行时,调试、新建断点、新建数据断点,地址:&b[10],字节计数:4,确定。
while (1) {//按F5,会停在下面某句,此时a的值为10,b[10]已经被修改为对应0..4之一。
b[(a=rand()%11)]=0;
Sleep(100);
b[(a=rand()%11)]=1;
Sleep(100);
b[(a=rand()%11)]=2;
Sleep(100);
b[(a=rand()%11)]=3;
Sleep(100);
b[(a=rand()%11)]=4;
Sleep(100);
}
return 0;
}
for( i = 2; i < list[0].data; i++,x++) // list[0].data 的值 = 数据总数+1
//越界访问应该是没有的,要是越界访问,调试的时候应该会出错。。不过你说的第二点,
//我感觉比较像出错原因。。。考虑到p1[10]=p2;//访问越界 不会发生。。
//就不太清楚了,我再看一下。。。多谢提示
int main()
{
int ** p1=(int**)malloc(sizeof(int)*10);
int *p2=(int *)malloc(sizeof(int));
p1[10]=p2;//访问越界
free(p1);//误以为p1[10]也是malloc地址,一起释放,导致free了无效空间造成堆破坏
return 0;
}