Segmentation Fault At First Frame

So, I’m making a game and it has a function called “createWindowAndInit” which initializes the SDL libraries and creates the window and renderer. This function also gets the information of the save data file and this is where the segmentation fault arises. After using GDB and valgrind I discovered what the error is and after a little testing discovered the general area where it is. So, it happens in both of the for loops inside of the function because if you remove both it’s fine.

This is the function where it occurs: int createWindowAndInit(){ if(SDL_Init(SDL_INIT_EVERYTHING) != 0){return SDL - Pastebin.com
And this is the whole code which you should not read entirely because if you do you will go insane: // Compile with: g++ main.cpp -lSDL2 -lSDL2_image -lSDL2_ttf -o "Five Nights At - Pastebin.com

You are corrupting the memory there:

void declareAnimationRects()
{
	for(int i = 0; i < sizeof(staticEffectRect); i++)
	{
		staticEffectRect[i].x = 0;
		staticEffectRect[i].y = 0;
		staticEffectRect[i].w = 1920;
		staticEffectRect[i].h = 1080;
	}
}

sizeof(staticEffectRect) == 128, You should calculate the length with sizeof(staticEffectRect) / sizeof(staticEffectRect[0]) or std::size(staticEffectRect). Ideally, with modern C++ You should use std::array and iterators/ranges.
Compile your program with -Og -g to get better debug experience.

1 Like

Thank you so much! This must’ve been so hard to track!

If you add -fsanitize=address,undefined (to clang, idr which one gcc supports) you might get runtime errors telling you the moment you corrupted something. But it isn’t guaranteed

1 Like