繁体   English   中英

C中的内存泄漏

[英]Memory Leaks in C

因此,我是C语言的新手,我正在为一个普通的位图图像识别程序编写一个矩阵压缩函数。 我有以下代码,Valgrind告诉我以下标记行有内存泄漏,尽管我不知道是什么原因造成的。 任何意见,将不胜感激。

/* Returns a NULL-terminated list of Row structs, each containing a NULL-terminated list of Elem   structs.
 * See sparsify.h for descriptions of the Row/Elem structs.
 * Each Elem corresponds to an entry in dense_matrix whose value is not 255 (white).
 * This function can return NULL if the dense_matrix is entirely white.
 */
Row *dense_to_sparse(unsigned char *dense_matrix, int width, int height) {
    Row *result = NULL;
    _Bool first_row;
    for (int row = height - 1; row >= 0; row--) {
        first_row  = 0;
        for (int elem = width - 1; elem >= 0; elem--) {
            unsigned char curr_item = dense_matrix[(row*width) + elem];
            if (curr_item!= 255) {
                if (!first_row) {
(Memory Leak)       Row *curr_row  = (Row *) malloc(sizeof(Row));
                    if (curr_row == NULL) {
                        allocation_failed();
                    }
                    curr_row->next = result;
                    curr_row->y = row;
                    curr_row->elems = NULL;
                    result = curr_row;
                    //free(curr_row);
                    first_row = 1;
                }
(Memory Leak)   Elem *curr_elem = (Elem *) malloc(sizeof(Elem));
                if (curr_elem == NULL) {
                    allocation_failed();
                }
                curr_elem->value = curr_item;
                curr_elem->x = elem;
                curr_elem->next = result->elems;
                result->elems = curr_elem;
                //free(curr_elem);
            }
        }
    }
    return result;
}

我相信释放curr_row和curr_elem可能是一个问题,尽管当我尝试在每个循环结束时释放它们时,它给了我运行时错误:

parsify(73897,0x7fff75584310)malloc: *对象0x7fbf81403a48错误:释放的对象的校验和不正确-释放后可能已修改了对象。

您需要从malloc获得的每个指针上调用free C不会自动释放您分配的内存,因此您需要告诉它“我完成了”。 免费是您的操作方式。

编辑:您可能还应该在函数的结尾处调用free ,这是在您知道内存已完成之后。 如果在循环结束时执行此操作,则在使用已经释放的内存时可能会遇到问题。

编辑编辑:释放它时,请注意,您已将结果放入curr_row->next 您可能稍后会free访问它,这是一个严重的问题。 您可能希望同时释放所有它们,因为显然您仍然需要内存(仍然有指向它的指针)。

您无法以dense_to_sparse free内存,因为该函数的重点是创建并返回新分配的数据结构。 大概,调用dense_to_sparse的代码想要使用结果。

您将需要一个单独的函数来释放不再需要的内存,以分配您应调用的内存。

void free_sparse_matrix (Row *matrix)
{
    Row *row = matrix;

    while (row != NULL) {
        Row *next_row = row->next;
        Elem *elem = row->elems;

        while (elem != NULL) {
            Elem *next_elem = elem->next;

            free (elem);
            elem = next_elem;
        }

        free (row);
        row = next_row;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM