簡體   English   中英

以下代碼可能導致分段錯誤?

[英]What could be causing segmentation fault in the following code?

我已經使用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作為輸入,但是它給出了分段錯誤。 可能導致這種情況發生的原因?

看起來您需要交換“寬度”和“高度”:

for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
        pixels[i][j] = fillcolor;
    }
}
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM