繁体   English   中英

尝试解除分配内存时出现堆错误

[英]Heap error while trying to deallocate memory

我编写了一个程序来分配一个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调用之前查看代码。

暂无
暂无

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

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