堆和堆碰撞时会发生什么 [英] What Happens When Stack and Heap Collide

查看:80
本文介绍了堆和堆碰撞时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道当堆栈和堆碰撞时会发生什么.如果有人遇到这种情况,请他们解释一下情况.

解决方案

在运行于现代OS上的现代语言中,您将得到堆栈溢出(欢呼!)或 malloc() sbrk() mmap()会在尝试增加堆时失败.但是并非所有软件都是现代软件,因此让我们看一下故障模式:

  • 如果堆栈增长到堆中,则通常的C编译器将以静默方式开始覆盖堆的数据结构.在现代操作系统上,将有一个或多个虚拟内存保护页,它们可以防止堆栈无限期增长.只要保护页中的内存量至少与增长过程的激活记录的大小一样大,操作系统就会向您保证存在段错误.如果您是在没有MMU的计算机上运行DOS,则可能是软管.

  • 如果堆增长到堆栈中,则操作系统应始终了解情况,并且某些类型的系统调用将失败. malloc()的实现几乎可以肯定会注意到失败,并返回 NULL .这取决于您.

我总是对编译器编写者愿意为操作系统放置保护页面以防止堆栈溢出而感到惊讶.当然,在您开始拥有成千上万的线程(每个线程都有自己的堆栈)之前,此技巧非常有效.

I am curious to know what happens when the stack and the heap collide. If anybody has encountered this, please could they explain the scenario.

解决方案

In a modern languages running on a modern OS, you'll get either a stack overflow (hurray!) or malloc() or sbrk() or mmap() will fail when you try to grow the heap. But not all software is modern, so let's look at the failure modes:

  • If the stack grows into the heap, the typically C compiler will silently start to overwrite the heap's data structures. On a modern OS, there will be one or more virtual memory guard pages which prevent the stack from growing indefinitely. As long as the amount of memory in the guard pages is at least as large as the size of the growing procedure's activation record, the OS will guarantee you a segfault. If you're DOS running on a machine with no MMU, you're probably hosed.

  • If the heap grows into the stack, the operating system should always be aware of the situation and some sort of system call will fail. The implementation of malloc() almost certainly notices the failure and returns NULL. What happens after that is up to you.

I'm always amazed at the willingness of compiler writers to hope that the OS puts guard pages in place to prevent stack overflow. Of course, this trick works well until you start having thousands of threads, each with its own stack...

这篇关于堆和堆碰撞时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆