&引用;realloc():下一个大小无效;
或者:副本 编译并运行此代码时,会收到一条错误消息: “realloc():下一个大小无效:0x0000000002483010” 在过去的6个小时里,我一直在试图找到一个解决办法,但没有一点运气 下面是我代码的相关部分-&引用;realloc():下一个大小无效;,c,C,或者:副本 编译并运行此代码时,会收到一条错误消息: “realloc():下一个大小无效:0x0000000002483010” 在过去的6个小时里,我一直在试图找到一个解决办法,但没有一点运气 下面是我代码的相关部分- #include<stdio.h> #include<stdlib.h> typedef struct vertex { char* name; int id; int outDegree; }vertex; int mai
#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;
}
#包括
#包括
typedef结构顶点
{
字符*名称;
int-id;
内倾度;
}顶点;
int main(){
顶点*tmpVertice;
顶点*顶点=(顶点*)calloc(1,sizeof(顶点));
int p=1;
虽然(p在第一次迭代时,您将访问顶点[p-1]=顶点[2-1]=顶点[1]
,但您只分配了1个字节(您只能访问顶点[0])。在必要时释放任何先前的缓冲区,因此循环中的行空闲(顶点)
和空闲(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;
}
intmain(){
顶点*tmpVertice;
顶点*顶点=空;
int p=1;
而(p你在调用realloc
后不需要free
。realloc
是否按未推荐的方式播放malloc
?tmpVertice=(顶点*)realloc(顶点,p)
阅读您试图使用的函数的文档如何?或者以谷歌搜索为例?@KevinDTimm是的,确实是。谢谢,但删除它们后,我仍然会收到相同的错误message@Roy我已经更新了我的答案,以涵盖您需要进行的其他更改谢谢!现在它可以工作了!谢谢您,但在将p更改为1后,我仍然是g设置相同的错误消息