简体   繁体   English

堆栈溢出在Linux上沉默?

[英]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 在Linux上我有一个代码,它使用在main函数内声明的数组,其中6e为2MB + 1字节

#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. 当我使用gcc在Linux上编译时,我运行它没有任何问题。 But on Windows I get a runtime error. 但是在Windows上我遇到了运行时错误。 At moment of run it I have 5GB of free memory. 在运行的那一刻,我有5GB的可用内存。

For solve the problem on Windows I need specify other stack size: 要解决Windows上的问题,我需要指定其他堆栈大小:

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? 因为在linux上编译的程序是在没有改变堆栈大小的情况下链接的?

Why it run ok on Linux but fail on Windows? 为什么它在Linux上运行正常但在Windows上运行失败? I use the same source code and the same gcc instructions: 我使用相同的源代码和相同的gcc指令:

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. 因为linux上的malloc实现我认为不可靠,因为它可以返回非空指针,即使内存不可用。

I think that in the program that is running on the Linux, it maybe silently ignore a stack problem?. 我认为在Linux上运行的程序中,它可能会默默地忽略堆栈问题?

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? 有可能是Linux上运行的程序没有链接改变堆栈大小,但在运行时不像Windows那样失败,是否会默默地忽略堆栈问题?

Also, why if I declare the array outside the main function it Works ok on Windows? 另外,为什么如果我在主函数之外声明数组它在Windows上正常工作? In case it use heap why I not need free it? 万一它使用堆为什么我不需要免费呢?

Why does it run fine on Linux but fails on Windows? 为什么它在Linux上运行良好但在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. 因为linux上的malloc实现我认为不可靠,因为它可以返回非空指针,即使内存不可用。

I suppose that you are talking about the overcommit issue . 我想你在谈论过度使用问题 To overcome this, you can use calloc and check the return value. 要解决此问题,您可以使用calloc并检查返回值。 If you do this at the very beginning of your application, you can immediately exit with an appropriate error message. 如果在应用程序的最开始执行此操作,则可以立即退出并显示相应的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM