I met with this error in my project. The related codes are as follows: I allocate memory for the pointer "values" as follows:
data->TSSet[0].values = (float *)malloc(sizeof(float)*10000);
Then after using it, I release the values as follows:
free(data->TSSet[0].values);
Then I met with the error munmap_chunk(): invalid pointer Aborted (core dumped). The pointer "values" is valid because when I try to print out the contents in "values", like follows:
for(i=0;i<TSSet[0].length;i++)
printf("%f\n",TSSet[0].values[i]);
I get the correct output. Why does the error happens? The full version of code is as follows:(I add comments on the key part, if you don't want to read the long code, just jump to the comments) In the main function, I just use ReadCSV(file, &data) to read in data, then immediately call ResetData(&data). Thank you all for helping me!!!!
void ReadCSV(char *file_path, DATA *Data){
Data->tsname = (char*)malloc(sizeof(char)*MAXNAME);
Data->TSSet = (TSItem*)malloc(sizeof(TSItem)*MAXNITEM);
FILE *fp = fopen(file_path, "r");
if(fp == NULL)
return ;
char line[MAXSTRL];
char *save_ptr,*tk;
int id = 0, num_class = 0, i,label;
Data->ls_class = (int *)malloc(sizeof(int)*MAXC);
Data->num_item = 0;
Data->length = 0;
while(fgets(line, sizeof(line), fp)) {
tk = strtok_r(line,",", &save_ptr);
if (tk == NULL)
return ;
label = atoi(trim(tk));
Data->TSSet[id].label = label;
Data->TSSet[id].num_nbr = 0;
if(IsExist(label,Data->ls_class, num_class) == 0){
Data->ls_class[num_class] = label;
num_class++;
}
// malloc the memory for values
Data->TSSet[id].values = (float *)malloc(sizeof(float)*MAXL);
Data->TSSet[id].knn = (Neighbor*)malloc(sizeof(Neighbor)*MAXK);
i=0;
// read in content of values from files
while(tk!=NULL){
tk = strtok_r(NULL,",", &save_ptr);
Data->TSSet[id].values[i] = strtof(trim(tk),NULL);
i++;
if(strlen(save_ptr) == 0)
break;
}
Data->TSSet[id].predlbl = -100;
Data->TSSet[id].conf = 0.0;
Data->TSSet[id].entropy = 0.0;
Data->TSSet[id].length = i;
id++;
}
if(fp == NULL)
printf("NULL!!!!!!!!!!!!!!!!!!!!!\n");
fclose(fp);
Data->num_item = id;
Data->length = i;
Data->num_class = num_class;
}
void ResetData(DATA *data){
int i;
free(data->tsname);
for(i=0;i<data->num_item;i++){
// error here
free(data->TSSet[i].values);
free(data->TSSet[i].knn);
}
free(data->TSSet);
data->num_item = 0;
data->num_class = 0;
free(data->ls_class);
data->length = 0;
return;
}