或者:重复面临错误 — glibc 检测到可用的无效下一个大小(快) https://stackoverflow.com/questions/2317021/facing-an-error-glibc-detected-free-invalid-next-size-fast.
当我编译并运行此代码时,我收到一条错误消息:
“realloc():下一个大小无效:0x0000000002483010”
在过去的 6 个小时里,我一直在努力寻找解决方案,但没有任何运气。
这是我的代码的相关部分-
#include<stdio.h>
#include<stdlib.h>
typedef struct vertex
{
char* name;
int id;
int outDegree;
}vertex;
int main(){
vertex *tmpVertice;
vertex *vertices = (vertex*)calloc(1, sizeof(vertex));
int p=1;
while(p<20){
vertex temp={"hi",p,0};
vertices[p-1]=temp;
tmpVertice=(vertex*)realloc(vertices,p);
if(tmpVertice!=NULL) vertices=tmpVertice;
p++;
}
return 0;
}
realloc http://linux.die.net/man/3/realloc如有必要,释放任何先前的缓冲区,以便行free(vertices)
and free(tmpVertice)
在你的循环中是错误的,应该被删除。
编辑:我在下面包含了您的程序的更新版本,并进行了进一步的修复。你需要realloc
p*sizeof(vertex)
而不是p
字节。你写的超出了数组的末尾然后增长它。我已经改为realloc
在循环开始时
int main(){
vertex *tmpVertice;
vertex *vertices = NULL;
int p=1;
while(p<20){
vertex temp={"hi",p,0};
tmpVertice=realloc(vertices,p*sizeof(vertex));
if(tmpVertice==NULL) {
printf("ERROR: realloc failed\n");
return -1;
}
vertices=tmpVertice;
vertices[p-1]=temp;
p++;
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)