Search code examples
cgcccompiler-constructionstructcygwin

Segmentation fault in Cygwin and default variable initialisation


Why does the if statement cause a segmentation fault when I compile in Cygwin ? Compiling in Linux via GCC works though.

After some research, I found out that it could be due to the fact that the struct int variable isn't initialised to 0 by default ?

However, doesn't C initialise all global and static variables to 0 ? The struct test is a global struct, so why doesn't it initialise to 0 ?

int x;  
int count = 20;

struct test {
        int ID;
       };
       typedef struct test GG;
       GG *ptr[200];

    int main(int argc, char const *argv[])
    {
        for(x = 0; x<count; x++) {
            if(!(*ptr[x]).ID){
                printf("true\n");
            }
        }
        return 0;
    }

Solution

  • GG *ptr[200]; ptr is an array of pointers to GG type of structure.You are trying to access these pointers which does not have any memory location.

    You need to allocate memory to each pointer of this array like below-

      for(x = 0; x<200; x++)
    ptr[x] = malloc(sizeof(struct test));