当 C 中的静态分配没有足够的内存时会发生什么? [英] What happens when there is not enough memory for a static allocation in C?

查看:60
本文介绍了当 C 中的静态分配没有足够的内存时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您动态分配内存时,例如malloc(1024 * sizeof(char)) 如果没有足够的内存来满足请求,结果指针将设置为 NULL.

When you dynamically allocate memory e.g. malloc(1024 * sizeof(char)) the resulting pointer is set to NULL if there is not enough memory available to fulfill the request.

当没有足够的内存来满足诸如 char c[1024] 之类的静态分配时会发生什么?

What happens when there is not enough memory to satisfy a static allocation such as char c[1024]?

推荐答案

char c[1024] 不一定是静态分配,它是静态的还是自动的,取决于声明是否写在一个函数(没有 static 修饰符)或在顶层.

char c[1024] is not necessarily a static allocation, it's static or automatic depending if the declaration is written inside the body of a function (without the static modifier) or at top-level.

静态分配不会在运行时失败,因为分配空间是在程序执行时保留的.如果不能保留足够的内存,程序将无法加载(exec* 在 Unix 上将失败).在病理情况下,内存可能被操作系统过度使用,系统只会在访问它时保留它.在这种情况下,分配失败将导致进程立即被系统杀死.

A static allocation cannot fail at run-time because the space for the allocation is reserved as the program is being executed. If sufficient memory cannot be reserved, the program will fail to load (exec* will fail on Unix). In pathological cases the memory could be overcommitted by the OS, and the system will only reserve it once it is accessed. In that case, failure to allocate will result in the process getting immediately killed by the system.

自动分配只是将堆栈的边缘向下移动,通常是通过递减堆栈指针寄存器.(这就是局部变量分配如此之快的原因.)C 程序没有可移植的机制来检测堆栈是否增长过大.一旦 MMU 检测到您已超过分配的限制,某些操作系统会自动增加堆栈;Linux 为主线程执行此操作,但不适用于进程中的其他线程.即便如此,足够的堆栈分配迟早会超过系统限制或耗尽系统内存而导致程序失败.

Automatic allocation simply moves the edge of the stack downward, typically by decrementing the stack pointer register. (This is why allocation of local variables is so fast.) A C program has no portable mechanism to detect that the stack has grown too large. Some operating systems will automatically grow the stack once the MMU detects that you have passed the allocated limit; Linux does this for the main thread, but not with other threads in a process. Even so, sufficient stack allocation will sooner or later surpass a system limit or will exhaust the memory of the system and the program will fail.

根据系统,程序要么立即因分段错误而失败,要么因堆栈和堆开始相遇时发生的内存损坏而死亡.

Depending on the system, the program will either immediately fail with a segmentation fault or it will die from memory corruption which happens when the stack and the heap start meet.

这篇关于当 C 中的静态分配没有足够的内存时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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