【问题标题】:Why is my cs50 speller code leaking memory?为什么我的 cs50 拼写代码会泄漏内存?
【发布时间】:2022-01-11 07:21:19
【问题描述】:

这是我的卸载函数:

for (int i = 0; i < N; i++)
{
   //line 116 
    while (table[i] != NULL)
    {
        node *tmp = table[i]->next;
        free(table[i]);
        table[i] = tmp;
    }
    return true;
}

check50 说我的代码正在泄漏内存。

这就是我的 malloc

while(fscanf(file, "%s", word) != EOF)
    {
        node *newNode = malloc(sizeof(node));

Help50 Valgrind 说: ==166== 条件跳转或移动取决于未初始化的值

看起来您正在尝试使用可能没有值的变量?仔细看看dictionary.c的第116行。

【问题讨论】:

  • 它说在哪里?还有其他信息吗?
  • 你是如何为这个表分配内存的?
  • 一般写成while table[i] != NULL) { node *tmp = table[i]; table[i] = table[i]-&gt;next; free (tmp); }
  • 如果 check50 说它正在泄漏内存,请务必自己运行 valgrind 以获取更多详细信息。

标签: c cs50


【解决方案1】:

假设你的数据结构如下:

const size_t N = /* some value */;

typedef struct _node {
    struct _node *next;
    int data;
} node;

node *table[N];

然后这个循环可靠地释放它的内存。我现在通过投影你有以下精神调试:

typedef struct _node {
    struct _node *next;
    char *data;
} node;

其中datastrdup() 或另一个malloc() 分配。在这种情况下,您需要按如下方式编辑循环体:

            node *tmp = table[i]->next;
            free(table[i]->data);
            free(table[i]);
            table[i] = tmp;

一般规则:结构中的指针在你释放结构时不会被释放,你必须自己做。

另一种可能性:

size_t N;
node **table;

在这种情况下你需要在卸载结束时

    free(table);
    table = NULL;
    N = 0;

如果这些都不正确,则您的泄漏在其他地方,不会在此函数中找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2011-10-21
    • 1970-01-01
    • 2019-09-08
    • 2020-10-04
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多