我正在尝试修复代码内的内存泄漏,但无法找到问题所在。有人可以帮我吗?这是我的源代码以及valgrind信息:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"
#include "utils.h"
int main()
{
p_hashTable hashTable;
int *auxArray, n;
scanf("%d", &n); // reads the number of patterns
auxArray = malloc(n * sizeof(int)); // array that holds sequences sizes
if (auxArray == NULL) {
exit(1);
}
char sequence[MAX];
int hashSize = n + (n/2); // Picking this size to avoid collisions
hashTable = create_hash_table(hashSize);
// Read each sequence, save its length and insert it in the hashtable
for (int i = 0; i < n; i ++)
{
scanf(" %s", sequence);
auxArray[i] = strlen(sequence);
insert(hashTable, sequence, i);
}
getchar();
char *dnaText = NULL;
int ch;
size_t size = 0, len = 0;
/* Read char by char, allocating memory space when needed */
while ((ch=getchar()) != EOF && ch != '\n') {
if (len + 1 >= size)
{
size = size * 2 + 1;
dnaText = realloc(dnaText, sizeof(char)*size); // realloc memory for the string
if (dnaText == NULL) {
return EXIT_FAILURE;
}
}
dnaText[len++] = ch;
}
dnaText[len] = '\0';
for (int i = 0; i < n; i ++)
{
if (alreadyExistsInArray(auxArray, i))
{
for (int x = 0; x < (strlen(dnaText) - auxArray[i] + 1); x++)
{
strncpy(sequence, dnaText + x, auxArray[i]);
sequence[auxArray[i]] = '\0';
findIndexInHash(hashTable, sequence);
}
}
printf("%d\n", returnNumberOfOccurences(hashTable, i));
}
free(dnaText);
free(auxArray);
free(hashTable->table);
free(hashTable);
return EXIT_SUCCESS;
}
Valgrind信息:总堆使用量:22个分配,15个空闲,147,304个字节分配
我想我的错误是在hashTable-> table上,但是我找不到解决方案。
编辑-hash.h代码
#include <stdlib.h>
#include <string.h>
#include "hash.h"
p_hashTable create_hash_table(int n)
{
p_hashTable ht = malloc(sizeof(HashTable));
if (ht == NULL)
{
exit(1);
}
ht->M = n;
ht->table = malloc(ht->M * sizeof(p_data));
if (ht->table == NULL)
{
exit(1);
}
for (int i = 0; i < ht->M; i ++)
{
ht->table[i] = malloc(sizeof(Data));
if (ht->table[i] == NULL)
{
exit(1);
}
ht->table[i]->counter = 0;
ht->table[i]->index = -1;
}
return ht;
}
int hash(p_hashTable ht, char *key)
{
int ret = 0;
for (int i = 0; i < strlen(key); i ++)
ret = (256 * ret + key[i]) % ht->M;
return ret;
}
int is_empty(p_hashTable ht, int i)
{
if (ht->table[i]->index == -1)
return 1;
else
return 0;
}
void insert(p_hashTable ht, char *key, int index)
{
int n = hash(ht, key);
int count = 0;
while (!is_empty(ht, n))
{
n = (n + 1) % ht->M;
count ++;
if (count >= ht->M)
{
exit(1);
}
}
strcpy(ht->table[n]->key, key);
ht->table[n]->index = index;
}
void findIndexInHash(p_hashTable ht, char *key)
{
int n = hash(ht, key);
int count = 0;
while (!is_empty(ht, n))
{
if (strcmp(ht->table[n]->key, key) == 0)
{
ht->table[n]->counter ++;
break;
}
n = (n + 1) % ht->M;
count ++;
if (count >= ht->M)
{
exit(1);
}
}
}
int returnNumberOfOccurences(p_hashTable ht, int index)
{
int i;
for (i = 0; i < ht->M; i ++)
if (ht->table[i]->index == index)
break;
return ht->table[i]->counter;
}