或者:面对错误的副本- glibc检测到免费无效的下一个大小(快).
当我编译并运行此代码时,我收到一条错误消息:"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;
}
Run Code Online (Sandbox Code Playgroud)
如果需要,realloc释放任何先前的缓冲区,因此行free(vertices)和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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
274 次 |
| 最近记录: |