* operation. */
 int dictReplace(dict *ht, void *key, void *val)
 {
-    dictEntry *entry;
+    dictEntry *entry, auxentry;
 
     /* Try to add the element. If the key
      * does not exists dictAdd will suceed. */
     /* It already exists, get the entry */
     entry = dictFind(ht, key);
     /* Free the old value and set the new one */
-    dictFreeEntryVal(ht, entry);
+    /* Set the new value and free the old one. Note that it is important
+     * to do that in this order, as the value may just be exactly the same
+     * as the previous one. In this context, think to reference counting,
+     * you want to increment (set), and then decrement (free), and not the
+     * reverse. */
+    auxentry = *entry;
     dictSetHashVal(ht, entry, val);
+    dictFreeEntryVal(ht, &auxentry);
     return 0;
 }
 
 
         tryObjectEncoding(c->argv[2]);
         /* note that c->argv[3] is already encoded, as the latest arg
          * of a bulk command is always integer encoded if possible. */
-        if (dictAdd(o->ptr,c->argv[2],c->argv[3]) == DICT_OK) {
+        if (dictReplace(o->ptr,c->argv[2],c->argv[3])) {
             incrRefCount(c->argv[2]);
         } else {
             update = 1;