BigMachine BigMachine - 1 year ago 72
C Question

segment fault, assigning to double pointer in c

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");

Answer Source

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.