glibc detected : double free or corruption

That’s because of this line : key+=sizeof(key); . key doen’t contain the same address as the malloc returned address.

For example:

char *key =(char*)malloc(sizeof(char) * 25);

Let’s say malloc returns the address 20000 (totally dumb address, it’s just for the example).

Now you’re doing key+=sizeof(key);, so key = 20000 + 4 = 20004. The problem is you’re trying to free key, which points to the address 20004 instead of 20000.

In order to fix that, try this:

int main()
{
    int cnt_map,i=1,value;
    char *key_save;

   /* My question is about this char pointer "key" */ 
    char *key =(char*)malloc(sizeof(char) * 25);

    key_save = key;
   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_save);
  } 
 }
return 0;
}

Leave a Comment