Petr Kučera Petr Kučera - 12 days ago 6
C Question

Segmentation fault 11 (probably in struct) before the main functin even started

I'd like to know where is the mistake in my code. I just started learning C and I just got to pointers and arrays so I have no idea where the mistake is. The problem seems to be in the part where I use struct to create my own data type because none of the debug texts that I've put in show themselves in console when I run the program. I've looked on the internet for an answer but haven t found anything. Any help would be appreciated.

#include <stdio.h>
#include <stdlib.h>
#define MAX_size 2000
typedef struct TMatrix{
int grid[MAX_size][MAX_size];
int sizex;
int sizey;
} TMATRIX;
int readSize(TMATRIX *matrix);

int main(void){
TMATRIX matrix;
printf("DEBUG\n");
if (readSize(&matrix)==1){
printf ("Invalid input.\n");
return 1;
}

printf("%d %d\n", matrix.sizex,matrix.sizey);

return 0;
}

int readSize(TMATRIX *matrix){
printf("DEBUG\n");
if (scanf("%d %d", &matrix->sizex, &matrix->sizey)!=2) return 1;
if (matrix->sizex<1 || matrix->sizey<1) return 1;

return 0;
}

Answer

In your TMATRIX structure, you declare an array of integers of 2000x2000.

2000*2000*4 is 16 megabytes. You're using an auto variable approx. that size (that if sizeof(int)==4 but that could be the double if sizeof(int)==8).

So you probably get a stack overflow before you even reach the first instruction, when the compiler-generated code tries to allocate enough stack room for your variable, typical stack sizes are smaller than that.

Fixes:

  • increase the stack (linker option)
  • use a global variable (move matrix outside the main procedure)
  • allocate your table using malloc, and not statically (to keep multidimensional aspect, define int (*grid)[MAX_size]; and make a malloc on MAX_size * sizeof *grid)