2012-03-13 81 views
1

我想使用OpenGL绘制Sierpinski carpet plane fractal,但我的程序不断收到SegFault错误。OpenGL程序中的分段错误

我的代码如下:

#include <GL/gl.h> 
#include <GL/glut.h> 
#include <stdlib.h> 
#include <math.h> 


class GLintPoint 
{ 
public: 
    GLint x, y; 
}; 

int random(int m) 
{ 
    return rand() % m; 
} 

void drawDot(GLint x, GLint y) 
{ 
    glBegin(GL_POINTS); 
    glVertex2i(x, y); 
    glEnd(); 
} 

void init() 
{ 
    glClearColor(1.0, 1.0, 1.0, 0.0); 
    glColor3f(0.0, 0.0, 0.0); 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    gluOrtho2D(0.0, 640.0, 0.0, 480.0); 
} 


int isSierpinskiCarpetPixelFilled(int x, int y, int width, int height) 
{ 

     GLintPoint point; 

     // base case 1 of 2 
     if ((x <= 0)||(y <= 0)||(x>=width)||(y>=height)) //top row or left column or out of bounds should be full 
     { 
      point.x = x; 
      point.y = y; 
      drawDot(point.x, point.y); 
     } 
     { 
       /* 
       If the grid was split in 9 parts, what part(x2,y2) would x,y fit into? 
       */ 
       int x2 = x * 3/width; // an integer from 0..2 inclusive 
       int y2 = y * 3/height; // an integer from 0..2 inclusive 

       // base case 2 of 2 
       if (x2 == 1 && y2 == 1) // if in the center square, it should be empty 
         return 0; 

       // general case 

       /* offset x and y so it becomes bounded by 0..width/3 and 0..height/3 
       and prepares for recursive call 
       some offset is added to make sure the parts have all the correct size when 
       width and height isn't divisible by 3 */ 

       x -= (x2 * width+2)/3; 
       y -= (y2 * height+2)/3; 
       width = (width +2-x2)/3; 
       height = (height+2-y2)/3; 
     } 


     return isSierpinskiCarpetPixelFilled(x, y, width, height); 
} 

void drawSierpinskiCarpet() 
{ 
    glClear(GL_COLOR_BUFFER_BIT); 
    glColor3f(0.0, 1.0, 0.0); 

    int x = 50; 
    int y = 50; 

    isSierpinskiCarpetPixelFilled(x,y,50,50); 

    glFlush(); 

} 


int main(int argc, char *argv[]) 
{ 
    glutInit(&argc, argv); 
    glutInitWindowSize(640,480); 
    glutInitWindowPosition(10,10); 
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); 
    glutCreateWindow("The Sierpinski Carpet"); 
    glutDisplayFunc(drawSierpinskiCarpet); 
    init(); 
    glutMainLoop(); 
    return EXIT_SUCCESS; 
} 
+0

如果你不叫里面drawSierpinskiCarpet isSierpinskiCarpetPixelFilled功能?这将帮助你本地化错误... – 2012-03-13 21:08:43

+0

你可以使用调试器/ GDB运行程序并告诉我们哪一行发生了段错误?我没有看到任何响铃警报,我只能说目前的代码中你的GLintPoint类是无用的。 – 2012-03-13 21:16:59

回答

4

很可能得到一个堆栈溢出。它似乎无限递归。到isSierpinskiCarpetPixelFilled导致另一个调用每次调用:

return isSierpinskiCarpetPixelFilled(x, y, width, height); 

在给定的输入值,输入参数(按顺序)为:

50, 50, 50, 50 
0, 0, 16, 16 
0, 0, 6, 6 
0, 0, 2, 2 
0, 0, 1, 1 
0, 0, 1, 1 
... (until stack overflow) 
+0

不是,其中一些返回0 – Imperian 2012-03-13 21:37:59

+1

是的,但如果至少有一个调用不返回0,则它将无限循环。 – 2012-03-13 21:40:05

+0

帝国:我添加了更多的信息来澄清。 – 2012-03-13 21:48:59