在以下代码中可能导致分段错误的原因是什么?

时间:2016-08-10 01:33:15

标签: c++ image-processing segmentation-fault

我使用640,480,0作为输入,但它给出了分段错误。什么可能导致这种情况发生?

/* Changes the size of an image, allocating memory as necessary, and
 setting all pixels to fillcolor. Returns 0 on success, or a non-zero error code.*/
int Image::resize( unsigned int width,  unsigned int height, uint8_t fillcolor ){
    if(pixels) {
        for(int i = 0; i < rows; i++) {
            delete[] pixels[i];
        }
        delete[] pixels;
    }

    pixels = new uint8_t*[height];

    if(pixels == NULL) {
        return 1;
    }

    for(int i = 0; i < height; i++)  {
        pixels[i] = new uint8_t[width];
        if(pixels[i] == NULL) {
            return 1;
        }
    }

    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            pixels[i][j] = fillcolor;
        }
    }

    cols = width;
    rows = height;
    return 0;
}

我使用640,480,0作为输入,但它给出了分段错误。什么可能导致这种情况发生?

2 个答案:

答案 0 :(得分:0)

看起来你需要交换“width”和“height”:

for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
        pixels[i][j] = fillcolor;
    }
}

答案 1 :(得分:0)

pixels = new uint8_t*[height];

这个二维数组的第一个维度是height

for (int i = 0; i < width; i++) {
    for (int j = 0; j < height; j++) {
        pixels[i][j] = fillcolor;
    }
}

此代码使用width作为pixels数组的第一维。第一个维度的范围从0到width-1,但它实际上包含0到height-1