-2

I have this C code:

#include <stdio.h>

int main(void)
{

    int courses = 1, groups, students = 54, average_pr_group;

    /* The variable groups is uninitialized */

    average_pr_group = students / groups;

    printf("Groups: %d\n", groups);

    printf("There are %d students pr. group in %d course(s)\n", average_pr_group, courses);

    return 0;
}

Now i compile this using this command from the shell (cmd):

gcc test.c -o test.exe -lm -Wall

It compiles fine, but when I try to run the generated .exe through Windows Explorer I get this error: Error running .exe file compiled with gcc

In contrast, I can compile & run this piece of code just fine:

# include <stdio.h>
int main()
{
    printf("Hello World");
    return 0;
}

I have MinGW installed at C:\MinGW This is my user PATH variable: User path variable

I can run the .exe just fine with msys, is it just built to withstand those kind of errors?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Jesse
  • 97
  • 2
  • 8
  • 3
    Your code is crashing. You haven't initialized `groups` and it's probably zero and you're dividing by 0. – indiv Sep 16 '14 at 17:16

2 Answers2

2

Variable groups is probably zero, therefore you divide by zero:

average_pr_group = students / groups;
Telvas
  • 158
  • 8
  • 1
    `groups` is uninitialized doesn't implies it has zero value. – Jack Sep 16 '14 at 17:23
  • Yes, it depends on used standard and compiler. Therefore I wrote "probably", as author did not provided such information. But thanks for pointing that out. – Telvas Sep 17 '14 at 17:07
  • so far I know, there's nothing in the C standard says locals should be zero value as default but that accessing them is UB. And I didn't know there are compilers that does defaults to 0 uninitialized variables. – Jack Sep 17 '14 at 20:26
  • Older versions of GCC (like 4.4) defaulted integers to zero without initialisation. – Telvas Sep 18 '14 at 08:47
1

as variable groups is uninitialized it has a undefined or garbage value and that's why the program is crashing...dividing by an uninitialized variable leads to crashing......

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59