Alternatively: duplicate of Facing an error — glibc detected free invalid next size (fast).
When I compile and run this code, I get an error message:
“realloc(): invalid next size: 0x0000000002483010”
I’ve been trying to find a solution for this for the last 6 hours without any luck..
Here are the relevant parts of my code-
#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 frees any previous buffer if necessary so the lines
free(vertices)andfree(tmpVertice)in your loop are wrong and should be removed.Edit: I’ve included an updated version of your program below with further fixes. You needed to
reallocp*sizeof(vertex)rather thanpbytes. You were writing beyond the end of the array then growing it. I’ve changed toreallocat the start of the loop