哈希表内存泄漏

时间:2014-09-25 05:28:08

标签: c memory-leaks hashtable

我有一个基本的哈希表实现,当我运行它时,一切都很好,但是 瓦尔格林德说我失去了一些记忆。

==11454== HEAP SUMMARY:
==11454==     in use at exit: 136 bytes in 1 blocks
==11454==   total heap usage: 10 allocs, 9 frees, 224 bytes allocated
==11454== 
==11454== LEAK SUMMARY:
==11454==    definitely lost: 136 bytes in 1 blocks
==11454==    indirectly lost: 0 bytes in 0 blocks
==11454==      possibly lost: 0 bytes in 0 blocks
==11454==    still reachable: 0 bytes in 0 blocks
==11454==         suppressed: 0 bytes in 0 blocks

我认为这可能是由于我将内存分配给我的键指针的方式。这是我的代码 表:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "htable.h"
#include "mylib.h"

struct htablerec {

  int capacity;
  int num_keys;
  char **keys;

};

static unsigned int htable_word_to_int(char *word) {
  unsigned int result = 0;
  while (*word != '\0') {
    result = (*word++ + 31 * result);
  }
  return result;
}

static unsigned int htable_hash(htable h, unsigned int i_key) {
  return i_key % h->capacity;
}

htable htable_new(int capacity) {

  int i;
  htable result = emalloc(sizeof *result);
  result->capacity = capacity;
  result->num_keys = 0;
  result->keys = emalloc(capacity * sizeof result->keys[0]);

  for (i = 0; i < capacity; i++) {

    result->keys[i] = NULL;
  }

  return result;
}

void htable_free(htable h) {

  int i;
l

  for (i = 0; i < h->capacity; i++) {

    free(h->keys[i]);
  }

  free(h);
}

int htable_insert(htable h, char *key) {

  unsigned int index = htable_word_to_int(key) % h->capacity;

  if (h->num_keys == h->capacity) {
    return 0;
  }
  for (;;) {

    if (NULL == h->keys[index]) {

      h->keys[index] = emalloc(sizeof(key));
      strcpy(h->keys[index], key);
      h->num_keys++;

      return 1;
    }
    if (strcmp(h->keys[index], key) == 0) {

      return 1;
    }
    index = htable_hash(h, index + 1);
  }
}

void htable_print(htable h, FILE *stream) {

  int i;

  for (i = 0; i < h->capacity; i++) {
    fprintf(stream, "%2d %s\n", i, h->keys[i] == NULL ? "" : h->keys[i]);
  }
}

emalloc函数只使用malloc并检查它是否正确分配了内存。另外,在我的 插入功能,我将关键字的大小。但关键是一个指针,所以不应该给我这么大的尺寸 指针不是单词?

1 个答案:

答案 0 :(得分:1)

  

&#34;我认为这可能是由于我为键盘指针分配内存的方式。&#34;

实际上,您正确地分配了键指针。它缺少free()它似乎是你的垮台:

result->keys = emalloc(capacity * sizeof result->keys[0]);

需要free()在某处。如:

void htable_free(htable h) 
{
   int i;
   for (i = 0; i < h->capacity; i++)
   {
       free(h->keys[i]);
   }
   free(h->keys); // NOTE: h->keys freed here.
   free(h);
}