【发布时间】:2012-10-15 08:13:59
【问题描述】:
我遇到以下代码的内存泄漏问题
static char **edits1(char *word)
{
int next_idx;
char **array = malloc(edits1_rows(word) * sizeof (char *));
if (!array)
return NULL;
next_idx = deletion(word, array, 0);
next_idx += transposition(word, array, next_idx);
next_idx += alteration(word, array, next_idx);
insertion(word, array, next_idx);
return array;
}
static void array_cleanup(char **array, int rows) {
int i;
for (i = 0; i < rows; i++)
free(array[i]);
}
static char *correct(char *word,int *count) {
char **e1, **e2, *e1_word, *e2_word, *res_word = word;
int e1_rows, e2_rows,max_size;
e1_rows = edits1_rows(word);
if (e1_rows) {
e1 = edits1(word);
*count=(*count)*300;
e1_word = max(e1, e1_rows,*count);
if (e1_word) {
array_cleanup(e1, e1_rows);
free(e1);
return e1_word;
}
}
*count=(*count)/300;
if((*count>5000)||(strlen(word)<=4))
return res_word;
e2 = known_edits2(e1, e1_rows, &e2_rows);
if (e2_rows) {
*count=(*count)*3000;
e2_word = max(e2, e2_rows,*count);
if (e2_word)
res_word = e2_word;
}
array_cleanup(e1, e1_rows);
array_cleanup(e2, e2_rows);
free(e1);
free(e2);
return res_word;
}
我不知道为什么 free() 不起作用。我在线程中调用这个函数“正确”,多个线程同时运行。我使用的是 Ubuntu 操作系统。
【问题讨论】:
-
您的免费功能在代码中哪里不起作用?如果它在任何地方都不起作用,您是否考虑过包含 malloc.h
-
您是否尝试过Valgrind 等工具来查找泄漏/内存问题?
-
@krammer 我没有包含 malloc.h ,它真的很重要吗?我的程序运行良好,除了内存泄漏问题
-
这是一些奇怪的代码。为什么你(可选)乘以 300 然后除以 300?考虑
#define一些常量。 -
AFAIR free() 只能释放由 *alloc() 函数分配的内存。我没有看到任何分配内存的代码...
标签: c memory-leaks pthreads malloc free