samedi 27 juin 2015

C Program crashes when accessing specific array element of struct field

I have this code:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct game_s {
  bool isOccupied[20][10];
};

int main() {
  struct game_s* game_p;
  game_p->isOccupied[0][8] = false;
  printf("0,8 works\n");
  game_p->isOccupied[2][8] = false;
  printf("2,8 works\n");
  game_p->isOccupied[1][7] = false;
  printf("1,7 works\n");
  game_p->isOccupied[1][9] = false;
  printf("1,9 works\n");
  game_p->isOccupied[1][8] = false; // crashes the program
  printf("1,8??");
}

As you can see from the comment, the program crashes when I try to access a specific element of the array. (More specifically, Windows tells me that "a.exe has stopped working" with the attached information.) If I use something other than 10 for the second dimension, the element will be another one. If I don't use a struct, it doesn't crash. If I use int instead of bool, it doesn't crash. If I make a variable of the struct instead of a pointer, it doesn't crash.

I'm compiling this with gcc main.c on Windows. If I use ideone, it runs without a problem.

Can someone tell me what's going on here?


Additional information Windows provides about the crash:

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: a.exe
  Application Version:  0.0.0.0
  Application Timestamp:    558f50c8
  Fault Module Name:    KERNELBASE.dll
  Fault Module Version: 6.1.7600.17206
  Fault Module Timestamp:   50e6605e
  Exception Code:   c0000005
  Exception Offset: 00011bcd
  OS Version:   6.1.7600.2.0.0.768.3
  Locale ID:    1031
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Read our privacy statement online:
  http://ift.tt/WDU7ZV

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

Aucun commentaire:

Enregistrer un commentaire