SEGFAULT occuring in C in raycaster due to incorrect high values being input into map array
11:30 17 Feb 2026

I've been following this raycaster tutorial as a fun project for myself: https://youtu.be/gYRrGTC7GtA?list=PLAaI2BTdQ5UNqKyp-0qwGzsU7U2DmeQmA&t=557

At the point in the video listed, the player is able to move around and cast a very basic ray that "detects" when a horizontal gridline is hit. For some reason in my code however, despite it being identical, this is not the case. Not only does the ray not correctly stop at wall edges but I have found that spinning in place by holding 'a' or 'd' can cause a SEGFAULT as for some reason at certain values, aTan=-1/tan(ra) produces values in the triple digits causing a cascading calculation error meaning that the map array is accessed with a very high value, causing the SEGFAULT.

This is strange as my code is essentially word for word copied from the video and near as I can tell the person doesn't experience the same issue. Additionally the player angle and thus ray angle are caught such that looking straight left or right is handled. I am at a loss as to why this is happening. Have I mistyped something or misunderstood what is going on in the code?

Included is the current extent of the function to eventually draw the "3D" walls of the world:

void drawRays3D()
{
    int r, mx, my, mp, dof; float rx, ry, ra, xo, yo;
    ra=pa;
    for(r=0;r<1;r++)
    {
        //Horizontal Line Check
        dof=0;
        float aTan = -1/tan(ra);
        if(ra>PI){ ry=(((int)py>>6)<<6)-0.0001; rx=(py-ry)*aTan+px;yo=-64;xo=-yo*aTan;}//looking up
        if(ra>6)<<6)+64;     rx=(py-ry)*aTan+px;yo= 64;xo=-yo*aTan;}//looking down
        if(ra==0 || ra==PI){rx=px;ry=py;dof=8;} //looking left or right
        while(dof < 8)
        {
            
            mx=(int)(rx)>>6;my=(int)(ry)>>6;mp=my*mapX+mx;
            if(mp>0 && (mp

Additionally for completeness this is the map array and player movement functions:

Map

//Game Map
int mapX = 8, mapY = 8, mapS = 64;
int map[]=
{
 1,1,1,1,1,1,1,1,
 1,0,1,0,0,0,0,1,
 1,0,1,0,0,0,0,1,
 1,0,1,0,0,0,0,1,
 1,0,0,0,0,0,0,1,
 1,0,0,0,0,1,0,1,
 1,0,0,0,0,0,0,1,
 1,1,1,1,1,1,1,1,   
};

Player Movement

void buttons(unsigned char key, int x, int y)
{
    if(key=='a'){pa-=0.1; if(pa<   0){pa+=2*PI;}pdx=cos(pa)*5;pdy=sin(pa)*5;}
    if(key=='d'){pa+=0.1; if(pa>   2*PI){pa-=2*PI;}pdx=cos(pa)*5;pdy=sin(pa)*5;}
    if(key=='w'){px+=pdx; py+=pdy;}
    if(key=='s'){px-=pdx; py-=pdy;}
    glutPostRedisplay();
}
c opengl segmentation-fault trigonometry glut