现在的位置: 首页 > 综合 > 正文

与realloc(): invalid next size:斗争了一天 总结

2013年09月09日 ⁄ 综合 ⁄ 共 1707字 ⁄ 字号 评论关闭
数据结构实验 要用顺序表实现栈

我想实现Push时栈空间不足就再申请
所以使用了realloc函数
以下代码编译通过 (gcc)
可是当我把栈元素类型换为double时
就出错了
郁闷

debug发现在第二次 realloc时出错

#include  <stdio.h>
#include  <stdlib.h>
#include  <string.h>

#define LIST_INIT_SIZE 1  //初始化时申请的大小
#define LIST_INCREMENT 1  //每次增加申请的大小

typedef  int ElemTypeOpnd; //栈元素的数据类型

typedef struct
{
ElemTypeOpnd *top;
int stacksize;
ElemTypeOpnd *base;
}SqOpnd;

void Init_SqOpnd(SqOpnd *L);
void PushOpnd(SqOpnd *L,ElemTypeOpnd e);

ElemTypeOpnd GetOpndTop(SqOpnd L);

ElemTypeOpnd GetOpndTop(SqOpnd L)
{
if(L.top==L.base)
{
printf("stack is null/n");
return;
}

return (*(L.top-1));
}

void PushOpnd(SqOpnd *L,ElemTypeOpnd e)
{
int lenth=(*L).top-(*L).base;
ElemTypeOpnd *newbase;
if(((*L).top-(*L).base)>=((*L).stacksize-1))
{

newbase=(ElemTypeOpnd*)realloc(((*L).base),((*L).stacksize+LIST_INCREMENT*sizeof(ElemTypeOpnd)));
if(!newbase)
exit(1);
(*L).base=newbase;
(*L).top=(*L).base+lenth;
(*L).stacksize+=LIST_INCREMENT;
//printf("new memory add/n");
}
*((*L).top)=e;
(*L).top++; //为double*时 第一次加2 第二此加8  实在诡异   
}

void Init_SqOpnd(SqOpnd *L)
{
(*L).base=malloc(LIST_INIT_SIZE*sizeof(ElemTypeOpnd));
if(!(*L).base)
exit(1);
(*L).top=(*L).base;
(*L).stacksize=LIST_INIT_SIZE;
}

int main(int argc, char *argv[])
{
printf("Hello, world!/n");
SqOpnd L;
 
Init_SqOpnd(&L);

PushOpnd(&L,81);
printf("%d/n",GetOpndTop(L));

PushOpnd(&L,82);
printf("%d/n",GetOpndTop(L));

PushOpnd(&L,83);
printf("%d/n",GetOpndTop(L));

PushOpnd(&L,84);
printf("%d/n",GetOpndTop(L));

return EXIT_SUCCESS;
}

后来在csdn论坛发帖解决了此问题
newbase=(ElemTypeOpnd*)realloc(((*L).base),((*L).stacksize+LIST_INCREMENT*sizeof(ElemTypeOpnd))); 
-->
newbase=(ElemTypeOpnd*)realloc(((*L).base),(((*L).stacksize+LIST_INCREMENT)*sizeof(ElemTypeOpnd))); 

 

总结如下
realloc不可怕
realloc(): invalid next size:0xxxx之类的错误

只是你给它的新空间比原空间小
仔细检查下 问题就解决了

抱歉!评论已关闭.