Frederico Jordan Frederico Jordan - 1 year ago 75
C Question

Segfault when passing structure from main() to worker functions

I am trying to write a simple game in C and I'm getting a SEGFAULT and have no idea why!

Here is the code for the program:

#include <stdio.h>
#include <string.h>

#define MAX_PLYS_PER_GAME (1024)
#define MAX_LEN (100)

typedef struct {
char positionHistory[MAX_PLYS_PER_GAME][MAX_LEN];
} Game;

void getInitialGame(Game * game) {
memset(game->positionHistory, 0, MAX_PLYS_PER_GAME*MAX_LEN*sizeof(char));

void printGame(Game game) {
printf("Game -> %p (%d)\n", &game, sizeof(game));

int hasGameEnded(Game game) {
return 0;

int main(int argc, char *argv[]) {
Game game;

if (hasGameEnded(game))
return -1;

return 0;

I tried debugging with gdb but the results didn't get me too far:

C:\Users\test>gdb test.exe
GNU gdb 5.1.1 (mingw experimental)
This GDB was configured as "mingw32"...
(gdb) run
Starting program: C:\Users\test/test.exe

Program received signal SIGSEGV, Segmentation fault.
0x00401368 in main (argc=1, argv=0x341c88) at fast-chess-bug.c:29
29 if (hasGameEnded(game))
(gdb) bt
#0 0x00401368 in main (argc=1, argv=0x341c88) at fast-chess-bug.c:29

cxw cxw
Answer Source

It is probably a stack overflow (really!), although I'm not sure.

  1. You are declaring Game game; in main(). That means all 102400 bytes of game are going on the stack.
  2. Both printGame and hasGameEnded take a Game game, NOT a Game * game. That is, they are getting a copy of the Game, not a pointer to the existing Game. Therefore, you dump another 102400 bytes on the stack whenever you call either one.

I am guessing that the call to printGame is clobbering the stack in a way that causes problems with the hasGameEnded call.

The easiest fix I know of (without getting into dynamic memory allocation, which may be better long-term) is:

  1. Move Game game; outside of main(), e.g., to the line just above int main(...). That way it will be in the data segment and not on the stack.
  2. Change printGame and hasGameEnded to take Game *:

    void printGame(Game * game) {
        printf("Game -> %p (%d)\n", game, sizeof(Game));
    int hasGameEnded(Game * game) {
        return 0;

That should get you moving forward.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download