c++ - 段错误 11 redux

标签 c++ opengl segmentation-fault glut

<分区>

我正在编写一个程序,该程序应在 640x480 窗口中的随机位置创建随机大小的绿色框​​。运行以下代码时出现段错误。问题在于两个“for”循环。段错误通常发生在带有 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).如果您从右下角开始,则无法创建超出数组边界的任何框。您的 randEnd 代码必须考虑添加到 randStartXrandStartY 时超出边界的框。 randEnd 需要受到约束,或者在您的 2 个 for 循环中,您需要确保将书写限制在显示区域(像素图)的边缘之外。

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

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

与:

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

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

关于c++ - 段错误 11 redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25952858/

相关文章:

python - 使用 Python 的 OpenGl

c++ - 第一人称相机移动问题

c++ - 变量改变它的值

c - 使用 getchar() 时 C 中的段错误

c - malloc 结构指针抛出段错误(核心已转储)

c++ - 做什么? XXX!yyyyyyyyyy+zzz 表示 !heap -flt s 输出

c++ - 将绑定(bind)函数分配给 std::function

c++ - C++中矩阵的输出不正确

c++ - 在 "if"语句中分配的内存,退出时释放

c++ - 用 GDB nexti 解释段错误的原因