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错误:释放的对象的校验和不正确-释放后可能已修改了对象。

您不能free在其中进行存储,dense_to_sparse因为该功能的全部目的是创建并返回新分配的数据结构。大概,调用的代码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;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章