简体   繁体   English

C中的堆栈溢出

[英]Stack overflow in C

If there is no memory left on the heap malloc will return NULL. 如果堆上没有剩余内存,则malloc将返回NULL。

Is the behaviour on stack overflow defined in C? 是否在C中定义了堆栈溢出行为?

Wikipedia suggests it's likely to cause a segfault, at least in the case of infinite recursion, but could something else happen? Wikipedia建议,至少在无限递归的情况下,它很可能导致段错误,但是还会发生其他情况吗?

Also in many managed environments, the runtime does not allow you to create arrays on the stack. 同样在许多托管环境中,运行时不允许您在堆栈上创建阵列。 Does that mean we should avoid it in native code too to guard against stack overflow, at least when the size of the array is determined at run time? 这是否意味着至少在运行时确定数组的大小时,我们也应避免在本机代码中使用它来防止堆栈溢出?

When you have a stack overflow, you are writing in unallocated memory. 当堆栈溢出时,您正在写未分配的内存。 The behaviour on writing in unallocated memory is undefined, but it will probably make your program crash. 在未分配的内存中写入数据的行为是不确定的,但这可能会使程序崩溃。

Does that mean we should avoid it in native code too to guard against stack overflow, at least when the size of the array is determined at run time? 这是否意味着至少在运行时确定数组的大小时,我们也应避免在本机代码中使用它来防止堆栈溢出?

Why would you avoid it? 为什么要避免呢? I would not avoid it because one benefit stack declared arrays have as compared to dynamic ones is that you don't have to bother with memory management issues (eg, no need to free ). 我不会避免这种情况,因为与动态数组相比,声明堆栈声明的数组具有的优势是您不必费心处理内存管理问题(例如,无需free )。 This is big plus. 这是一大优势。

In rare cases if the array you want is too big and won't fit on stack, you can use dynamic arrays. 在极少数情况下,如果所需的数组太大而不能放在堆栈中,则可以使用动态数组。 There are some estimates on stack sizes too, on Windows for example in Visual Studio default stack size is 1MB. 堆栈大小也有一些估计,例如在Windows上,例如在Visual Studio中,默认堆栈大小为1MB。 You can consider this. 您可以考虑一下。 This size can also be increased if I am not wrong. 如果我没记错的话,这个大小也可以增加。

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

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