segment fault, assigning to double pointer in c

邮差的信 提交于 2021-01-29 04:10:04

问题


I am getting a little confused as to how to properly allocate memory for double pointers.

My code causes a segment fault the second time it attempts to store a value at the 2nd index of the first UCHAR pointer array.

Any assistance would be appreciated.

assigning my double pointer:

        width = BMP_GetWidth (bmp);
        height = BMP_GetHeight (bmp);
        depth = BMP_GetDepth (bmp);

        r = (UCHAR **) malloc(sizeof(UCHAR *) * height);
        g = (UCHAR **) malloc(sizeof(UCHAR *) * height);
        b = (UCHAR **) malloc(sizeof(UCHAR *) * height);

        init_rgb(bmp, width, height, r, g, b);

attempting to utilize the pointer (fails on x = 1):

void init_rgb(BMP *bmp, UINT w, UINT h, UCHAR **r, UCHAR **g, UCHAR **b) {
        printf("%ld, %ld\n", w, h);
        UINT x, y;
        for (y = 0; y < h; y++) {
            r[y] = (UCHAR *)malloc(sizeof(UCHAR) * w);
            for (x = 0; x < w; x++) {
                BMP_GetPixelRGB(bmp, x, y, &r[y][x], &g[y][x], &b[y][x]);
                printf("FAILING After First Iteration\n");
            }
        }
    }

回答1:


Looks like you need a line like

r[y] = (UCHAR *)malloc(sizeof(UCHAR) * w);

for g and b as well. If you don't do that, g[y] and b[y] are undefined. Your code is probably failing when you reference those.



来源:https://stackoverflow.com/questions/39322360/segment-fault-assigning-to-double-pointer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!