c - 尝试释放内存时出现堆错误

标签 c memory memory-management memory-address

我编写了一个程序来分配 PIXEL 矩阵,每个 PIXEL 都是一个包含以下内容的结构:

typedef struct Pixel {
    unsigned char red;
    unsigned char green;
    unsigned char blue;
    unsigned char gray;
} PIXEL;

每个矩阵都使用以下函数进行分配:

PIXEL** createImageMatrix(FILE *fp, int height, int width)
{
    PIXEL **res;
    int i, j;

    res = (PIXEL**)malloc(sizeof(PIXEL*)*height);
    checkalloc(res);

    printf("-->createImageMatrix()\n");
    for (i = 0; i < height; i++)
    {
        res[i] = (PIXEL*)calloc(width, sizeof(PIXEL));
        checkalloc(res[i]);
        printf("matrix[%d]: %p \n", i, res[i]);
    }
    printf("<--createImageMatrix()\n");
    return res;
}

并使用以下函数释放:

void freeImageMatrix(PIXEL **matrix, int height)
{
    int i;

    printf("-->freeImageMatrix()\n");
    for (i = 0; i < height; i++)
    {
        printf("matrix[%d]: %p \n", i, matrix[i]);
        free(matrix[i]);
    }
    printf("<--freeImageMatrix()\n");
    free(matrix);
}

freeImageMatrix()的调用如下:

freeImageMatrix(matrix, height);

为了调试问题,我在分配地址、获取值以及尝试释放它们时打印地址。这是命令行上的输出:

-->createImageMatrix()
matrix[0]: 0x00881AA8
matrix[1]: 0x00881AE8
matrix[2]: 0x00881B28
matrix[3]: 0x00881B68
matrix[4]: 0x00881BA8
<--createImageMatrix()
-->freeImageMatrix()
matrix[0]: 0x00881AA8
Press any key to continue . . .

弹出的错误窗口显示以下内容:

HEAP CORRUPTION DETECTED: after Normal block (#79) at 0x0061AA8.
CRT detected that the application wrote to memory after end of heap buffer.

我分配并尝试取消分配的地址匹配,那么天哪,为什么这种情况会发生在我身上?

添加

checkalloc():

void checkalloc (void* memory)
{
    if (memory==NULL)
    {
        printf("\nMemory allocation failed!\n");
        free(memory);
        exit (1);
    }

这就是矩阵中的值获取其值的方式:

    for (j = 0; j < width; j++)
    {
        fscanf(fp, "%u", &(res[i][j]).red);
        fscanf(fp, "%u", &(res[i][j]).green);
        fscanf(fp, "%u", &(res[i][j]).blue);
        res[i][j].gray = (res[i][j].red + res[i][j].green + res[i][j].blue) / 3;
    }

最佳答案

程序中的其他地方存在一个错误,该错误正在破坏堆,当您尝试从堆中释放某些内容时,该错误恰好会显现出来。

我会在 freeImageMatrix 调用之前查看代码。

关于c - 尝试释放内存时出现堆错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18379265/

相关文章:

c - 任何具有 C 输出的 C 编译器?

memory - 在 VB6 应用程序中识别内存占用的工具

Python:计算成对距离会导致内存错误

c - 越界访问数组有多危险?

c++ - 在线编译器对计算机内存的影响

c++ - 区分 C++ 对象是否动态分配?

C - 结构中的结构数组在 dfa 程序中返回意外结果

c - %s 和 %1024s 之间的差异

c++ - C 结构中的内存对齐

ios - iOS 应用程序可以在后台收到内存警告吗?