从 C 中的多维数组访问数据时偶尔出现意外输出

Occasional unexpected output when accessing data from multidimensional array in C

我有一段代码将图像中的字节存储到存储在结构中的多维数组中。在将字节分配给数组时,预期数据(0xFF,因为我正在使用纯白色图像进行测试)和数组实际指向的数据 pixel_array[i][j][k] 匹配.这是在数组中存储数据的代码片段:

unsigned char pixel[bmp_image->pixel_width];
bmp_image->pixel_array = malloc(bmp_image->width * sizeof(unsigned char));

for (int i = 0; i < bmp_image->width; i++) {
    bmp_image->pixel_array[i] = malloc(bmp_image->height * sizeof(unsigned char));

    for (int j = 0; j < bmp_image->height; j++) {
        bmp_image->pixel_array[i][j] = malloc(bmp_image->pixel_width * sizeof(unsigned char));
        fread(pixel, sizeof(pixel), 1, bmp_data);

        // Pixel width refers to the size of a pixel in bytes
        for (int k = 0; k < bmp_image->pixel_width; k++) {
            bmp_image->pixel_array[i][j][k] = pixel[k];
            // These two print statements always result in the same data (i.e. both print 0xFF for the white test image)
            printf("Expected byte: %x\n", pixel[k]);
            printf("Saved byte: %x\n\n", bmp_image->pixel_array[i][j][k]);
        }
    }

    fseek(bmp_data, padding, SEEK_CUR);
}

这是存储图像数据的结构:

struct Image {
    FILE *image_file;
    int width;
    int height;
    int pixel_width;
    int error_code;
    unsigned char*** pixel_array;
};

我的问题是,一旦我尝试使用以下代码访问存储在像素数组中的字符,我就会得到随机的意外输出(即不是十六进制 FF)

for (int i = 0; i < bmp_image->width; i++) {
    for (int j = 0; j < bmp_image->height; j++) {
        for (int k = 0; k < bmp_image->pixel_width; k++) {
            printf("%x", bmp_image->pixel_array[i][j][k]);
        }
    }
}

下面是一个 10x10 白色图像的输出示例(预计只有 ff):

6050a3c051a32053a38054a3e055a34057a3ffffffffffffffffffffffffc04ca3404da3fffffffffffffffffffffffff
fffffffffffffffffffffff204ea3a04ea3ffffffffffffffffffffffffffffffffffffffffffffffff804fa3050a3fff
fffffffffffffffffffffffffffffffffffffffffffffe050a36051a3ffffffffffffffffffffffffffffffffffffffff
ffffffff4052a3c052a3ffffffffffffffffffffffffffffffffffffffffffffffffa053a32054a3fffffffffffffffff
fffffffffffffffffffffffffffffff055a38055a3ffffffffffffffffffffffffffffffffffffffffffffffff6056a3e
056a3ffffffffffffffffffffffffffffffffffffffffffffffffc057a34058a3ffffffffffffffffffffffffffffffff
ffffffffffffffff

随机数据似乎总是在相同的位置,但每次的值都不同。我假设我 运行 遇到了一些错误分配指针的问题,但到目前为止,我对可能导致它的原因感到困惑。

看来你分配的内存不够

bmp_image->pixel_array[i] = malloc(bmp_image->height * sizeof(unsigned char));

它为 bmp_image->height 分配内存,而它应该为 bmp_image->height 指针 分配资源。一个有助于避免此类错误的好模式是:

x = malloc(sizeof *x);

对于这种情况,它将是:

bmp_image->pixel_array[i] = malloc(bmp_image->height * sizeof(*bmp_image->pixel_array[i]));

我假设 bmp_image->pixel_array 在使用前已正确分配。