I will explain the brief coding steps I have done and area where I am facing the problem
main.cpp
int main()
{
int cnt_map,i=1,value;
/* My question is about this char pointer "key" */
char *key =(char*)malloc(sizeof(char) * 25);
if(key!=NULL)
{
printf("Key value is not NULL,its value is:%x\n",key) ;
cout<< "Enter the number of elements required in container map"<<endl;
cin >> cnt_map;
for (i=1;i<=cnt_map;i++)
{
cout << "Enter the key : ";
cin >>key;
cout << "Enter the key value:" ;
cin >>value;
printf("value pointed by ptr key: %s, value in ptr: %x\n", key,key);
c -> add_map1(key,value); //Function inserts value to map container
key+=sizeof(key);
}
c -> size_map1(); //Function displays size of map container
c -> display_map1(); //Function displays contents of map container
if(key)
{
printf("FINALLY:value pointed by ptr key: %s, value in ptr: %x,size:%d\n",key, key, sizeof(key));
free(key);
}
}
return 0;
}
when tried compiling and running the above code, I am able to successfully compile the code but got "glibc detected : double free or corruption" when tried running the application.
Now my question is I created a char pointer(char *key =(char*)malloc(sizeof(char) * 25);
)
and successfully assigned memory to it using malloc. After completing my process when I tried freeing of that char pointer I am getting double free or corruption error. I learned that any variable assigned memory with malloc/calloc should be freed finally. Please tell why I am this getting error, why I should not do this? Please tell me how the memory operations are ongoing on char* key
(if possible pictorially).
Note: The code presented above is not the complete code, I just explained where I am getting the problem and if I am not freeing the pointer variable, my application is running successfully.