diff --git a/sql/item_func.cc b/sql/item_func.cc
index 91c8a1ffdff4ab4124bbd0d2147a33497afb71dd..6296c2981aa9f43910ab4a464985de8c4046ff44 100644
--- a/sql/item_func.cc
+++ b/sql/item_func.cc
@@ -3682,8 +3682,9 @@ update_hash(user_var_entry *entry, bool set_null, void *ptr, uint length,
 	char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
 	if (entry->value == pos)
 	  entry->value=0;
-	if (!(entry->value=(char*) my_realloc(entry->value, length,
-					      MYF(MY_ALLOW_ZERO_PTR))))
+        entry->value= (char*) my_realloc(entry->value, length,
+                                         MYF(MY_ALLOW_ZERO_PTR | MY_WME));
+        if (!entry->value)
 	  return 1;
       }
     }
diff --git a/storage/heap/hp_block.c b/storage/heap/hp_block.c
index 35e65a94603177a2b8124ca1eeba3e84a1abcda6..85219380287d2b27f7eaa797f708da3c5fcf7b07 100644
--- a/storage/heap/hp_block.c
+++ b/storage/heap/hp_block.c
@@ -75,7 +75,7 @@ int hp_get_new_block(HP_BLOCK *block, ulong *alloc_length)
     and my_default_record_cache_size we get about 1/128 unused memory.
    */
   *alloc_length=sizeof(HP_PTRS)*i+block->records_in_block* block->recbuffer;
-  if (!(root=(HP_PTRS*) my_malloc(*alloc_length,MYF(0))))
+  if (!(root=(HP_PTRS*) my_malloc(*alloc_length,MYF(MY_WME))))
     return 1;
 
   if (i == 0)
diff --git a/storage/heap/hp_write.c b/storage/heap/hp_write.c
index f8b268ee06ad6bed87e2910500fd622daa09e6ec..86e79c9d7ecbab87e91c0dc9db12f4b2d4713fe5 100644
--- a/storage/heap/hp_write.c
+++ b/storage/heap/hp_write.c
@@ -67,11 +67,17 @@ int heap_write(HP_INFO *info, const byte *record)
   DBUG_RETURN(0);
 
 err:
-  DBUG_PRINT("info",("Duplicate key: %d", (int) (keydef - share->keydef)));
+  if (my_errno == HA_ERR_FOUND_DUPP_KEY)
+    DBUG_PRINT("info",("Duplicate key: %d", (int) (keydef - share->keydef)));
   info->errkey= keydef - share->keydef;
-  if (keydef->algorithm == HA_KEY_ALG_BTREE)
+  /*
+    We don't need to delete non-inserted key from rb-tree.  Also, if
+    we got ENOMEM, the key wasn't inserted, so don't try to delete it
+    either.  Otherwise for HASH index on HA_ERR_FOUND_DUPP_KEY the key
+    was inserted and we have to delete it.
+  */
+  if (keydef->algorithm == HA_KEY_ALG_BTREE || my_errno == ENOMEM)
   {
-    /* we don't need to delete non-inserted key from rb-tree */
     keydef--;
   }
   while (keydef >= share->keydef)