我写了一个程序来分配一个像素矩阵,每个像素都是一个结构,它包含:
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;
}