C中的内存泄漏

Bra*_*onM 1 c memory-leaks

所以我对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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 7

你需要调用free你得到的每个指针malloc.C不会自动释放你分配的内存,所以你需要告诉它"我已经完成了".免费是你如何做到这一点.

编辑:free在你知道你完成了内存之后,你也应该在函数的最后调用.如果在循环结束时执行此操作,则可能会遇到使用已释放内存的问题.

编辑编辑:当你释放它时,请注意你已经把结果放入curr_row->next.您可能稍后访问此帖子free,这是一个严重的问题.您可能希望同时释放所有这些内容,因为显然您仍然需要内存(您仍然需要指向它).