Stack overflow silenced on linux?

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("Byen");

    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?


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

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

  • On Windows, the default stack reservation size used by the linker is 1 MB.
  • On Linux/Unix, the maximum stack size can be configured through the ulimit command. In addition, you can configure the stack size when creating a new thread.
  • 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.

    链接地址: http://www.djcxy.com/p/28344.html

    上一篇: 堆数组分配而不是堆栈

    下一篇: 堆栈溢出在Linux上沉默?