640x480 창의 임의의 위치에 임의의 크기의 녹색 상자를 만들어야하는 프로그램을 작성했습니다. 다음 코드를 실행하면 분할 오류가 발생합니다. 문제는 두 개의 "for"루프에 있습니다. 일반적으로 segfault는 startx가있는 중첩 된 "for"루프에서 발생합니다. 나는 버퍼 오버 플로우를 의심하지만, 덜 부피가 큰 코드를 만드는 방법을 모른다.세그먼트 오류 11 redux
//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;
}
어떤 원인 일 수 있습니까? 여기에 뻔뻔한 논리 문제가 있습니까? 미리 감사드립니다.
'pixmap'의 선언과 그것을 초기화하는 코드를 보여줄 수 있습니까? –
"부피가 큰 코드"는 버퍼 오버 플로우와 어떤 관련이 있습니까? 그냥'pixmap'에 적당한 공간을 할당했는지 확인하십시오. – Barmar
'너비 및 높이'란 무엇입니까? 'starty == height-1'과'endy == starty + randEnd', 너비'randEnd> 0'을 가진 상자를 만들면 버퍼 밖에 쓸 수있는 것처럼 보입니다. –