[英]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.