I'm having trouble with freeing memory after allocation using Calloc()
, and I get the error free(): invalid next size (fast)
.
After reading many answers for similar problems I came to a conclusion (or at least, I think), that I don't have enough memory to call free()
, and therefore encounter this problem.
Do I allocate enough memory at first place? Is there any thumb rule for allocating? I'm getting kind of lost with that problem.
Here is the part of the code where I try to use free():
void read_mat(mat *matrix, char *str){
char *p, *q;
char c;
int count = 0, i = 0, j = 0, buff = 8, row = 0, col = 0;
float num;
p = (char *)calloc(buff, sizeof(char));
free(p);
/* ignore the line above, I've tested if I can free that pointer right away, and failed. */
while (count <= (pow(DIM, 2))){
c = *(str + i);
if (c == EOF || c == '\0' || c == ','){
num = atof(p);
matrix -> matrix[col][row] = num;
col++;
if (col == 4){
col = 0;
row++;
}
count++;
i++;
buff = 8;
j = 0;
free(p);
p = (char *)calloc(buff, sizeof(char));
if (c == EOF || c == '\0')
break;
}
else if (c == ' '){
i++;
continue;
}
else {
p[j] = c;
i++;
j++;
if (j == buff - 1){
buff *= 2;
q = (char *)realloc(p, buff);
if (!q){
printf("read_mat: Memory allocation failed\n");
return;
}
p = q;
}
}
}
if (p != NULL)
free(p);
}