3

On Linux I have a code that use a array declared inside the main function with a sixe of 2MB + 1 byte

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

#define MAX_DATA (2097152)  /* 2MB */

int main(int argc, char *argv[])
{
    /* Reserve 1 byte for null termination */
    char data[MAX_DATA + 1];

    printf("Bye\n");

    return 0;
}

When I compiled on Linux with gcc I run it without any problem. But on Windows I get a runtime error. At moment of run it I have 5GB of free memory.

For solve the problem on Windows I need specify other stack size:

gcc -Wl,--stack,2097153 -o test.exe test.c

or declare the data array outside the main function.

Because that the program compiled on linux was linked without change the stack size?

Why it run ok on Linux but fail on Windows? I use the same source code and the same gcc instructions:

gcc -Wall -O source.c -o source

Because malloc implementation on linux i think is not reliable because it can return a not null pointer even if memory is not available.

I think that in the program that is running on the Linux, it maybe silently ignore a stack problem?.

Is possible that the program that is running on Linux that was not linked changing the stack size, but not fail at runtime unlike Windows, is silently ignoring a stack problem?

Also, why if I declare the array outside the main function it Works ok on Windows? In case it use heap why I not need free it?

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
carlos
  • 1,261
  • 1
  • 12
  • 15

1 Answers1

9

Why does it run fine on Linux but fails on Windows?

Because the default stack size for a process or thread is system dependant:

Because malloc implementation on linux i think is not reliable because it can return a not null pointer even if memory is not available.

I suppose that you are talking about the overcommit issue. To overcome this, you can use calloc and check the return value. If you do this at the very beginning of your application, you can immediately exit with an appropriate error message.

Community
  • 1
  • 1
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • thanks. today I learn about the 1mb default stack size on windows. Seems that on Linux this size is greather than Windows like 8Mb normally. Then if it not crash on Linux is ok, I will not need patch the program. – carlos Mar 11 '14 at 12:25
  • 3
    @carlos: Yes, instead of patching the program, you only need to patch Windows to make it work... ;-) – Brendan Mar 11 '14 at 12:26