分段故障11冗余

Segmentation Fault 11 redux

本文关键字:冗余 故障 分段      更新时间:2023-10-16

我正在编写一个程序,该程序应该在640x480窗口中的随机位置创建随机大小的绿色框。运行以下代码时出现分段错误。问题在于两个"for"循环。segfault通常出现在带有startx的嵌套"for"循环中。我怀疑是缓冲区溢出,但不知道如何制作体积较小的代码。

//Globals
int width, height;
int endx, endy, starty, startx, randEnd, randStartX, randStartY;
unsigned char *pixmap;
void setPixels(){
for (int j = 1; j<100; j++) { // j == j-1 # of boxes
    randStartX = rand() % width; // random # btw 0 and width
    randStartY = rand() % height; // random # btw 0 and height
    randEnd = 1 + (rand() % 100); // random # btw 0 - 100, not allowing box > 100.
    startx = randStartX;
    starty = randStartY;
    endx = startx + randEnd;
    endy = starty + randEnd;
    for(int y = starty; y < endy; y++) { // first y coordinate of box
        for(int x = startx; x < endx; x++) { // first x coordinate of box
            cout << "endx = " << endx << endl;
            int i = (y * width + x) * 3; // movement upwards for each pixel
            pixmap[i++] = 0x00; //Increments i by one to move to the next part of pixel.
            pixmap[i++] = 0xFF; 
            pixmap[i] = 0x00; 
            }
        }
    }
}
int main(int argc, char *argv[])
{
    //initialize the global variables
    srand (time(0));
    width = 640;
    height = 480;
    pixmap = new unsigned char[width * height * 3];  
    setPixels(); // write code like ./pr01 red, etc.
    glutInit(&argc, argv);
    glutInitWindowPosition(100, 100); // Where the window will display on-screen.
    glutInitWindowSize(width, height);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutCreateWindow("Assignment 01");
    init();
    glutReshapeFunc(windowResize);
    glutDisplayFunc(windowDisplay);
    glutMouseFunc(handleButton);
    glutMainLoop();
    return 0; 
}

你知道是什么原因造成的吗?这里有明显的逻辑问题吗?提前谢谢。

如何看待这个问题是假设randStartX设置为639,randStartY设置为479。现在你们说找一个随机数来确定盒子的大小(最大100)。若从右下角开始,则不能创建超出数组边界的任何长方体。当添加到randStartXrandStartY时,您的randEnd代码必须考虑超出界限的框。randEnd需要被约束,或者在你的2 for循环中,你需要确保你将书写约束在显示区域(像素图)的边缘之外。

最好的方法是约束endxendy。你可以这样做,并通过更换来修复你的错误

endx = startx + randEnd;
endy = starty + randEnd;

带有:

endx = min(startx + randEnd, width-1);
endy = min(starty + randEnd, height-1);

使用min函数来限制框,使其不会超出widthheight的边缘(由于我们基于0,因此减去1)

当然,如果startx/y可以在0..width/height-1范围内,randEnd在1..100范围内,则endx/y很容易溢出(例如startx=width-30和randEnd=80)。

这是您的问题,如注释中所述。使用下面的代码,您将只填充内部缓冲区。

for(int y =0; y < randStartY ; y++) { // first y coordinate of box
    for(int x = 0; x < randStartX; x++) { // first x coordinate of box
        //cout << "endx = " << endx << endl;
        int i = (y * width + x) * 3; // movement upwards for each pixel
        pixmap[i++] = 0x00; //Increments i by one to move to the next part of pixel.
        pixmap[i++] = 0xFF; 
        pixmap[i] = 0x00; 
        }
    }
}

既然你只是在这里处理颜色,我想这就是你想要的。如果你想复制一个纹理,我们必须用一些偏移和其他东西来做一些不同的事情:)

不管怎样,我希望它能有所帮助。

干杯