堆内存分配 [英] Heap memory allocation

查看:90
本文介绍了堆内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用malloc()在程序中动态分配内存,但在程序运行时没有释放内存,那么在程序终止后动态释放的内存会被释放吗?

If I allocate memory dynamically in my program using malloc() but I don't free the memory during program runtime, will the dynamically allocated memory be freed after program terminates?

或者,如果它没有被释放,而我又一次又一次地执行相同的程序,它将每次分配不同的内存块吗?如果是这种情况,我应该如何释放该内存?

Or if it is not freed, and I execute the same program over and over again, will it allocate the different block of memory every time? If that is the case, how should I free that memory?

注意:我能想到的一个答案是重新启动执行程序的计算机.但是,如果我要在远程计算机上执行程序,并且重启不是一种选择吗?

Note: one answer I could think of is rebooting the machine on which I am executing the program. But if I am executing the program on a remote machine and rebooting is not an option?

推荐答案

简短的回答:一旦进程终止,任何合理的操作系统都将释放该进程分配的所有内存.因此,不可以,当您多次重新启动进程时,内存分配将不会累积.

Short answer: Once your process terminates, any reasonable operating system is going to free all memory allocated by that process. So no, memory allocations will not accumulate when you re-start your process several times.

进程和内存管理通常是操作系统的责任,因此,在进程终止后是否释放分配的内存实际上取决于操作系统.不同的操作系统对内存管理的处理方式可能不同.

Process and memory management are typically a responsibility of the operating system, so whether allocated memory is freed or not after a process terminates is actually dependent on the operating system. Different operating systems can handle memory management differently.

也就是说,任何合理的操作系统(尤其是多任务操作系统)都将释放该进程终止后分配给该进程的所有内存.

That being said, any reasonable operating system (especially a multi-tasking one) is going to free all of the memory that a process allocated once that process terminates.

我认为其背后的原因是操作系统必须能够正常处理不规则情况:

I assume the reason behind this is that an operating system has to be able to gracefully handle irregular situations:

  • 恶意程序(例如那些有意释放内存的程序,以期影响运行它们的系统)
  • 程序异常终止(即程序意外结束,因此可能没有机会显式地free动态分配的内存本身的情况)
  • malicious programs (e.g. those that don't free their memory intentionally, in the hope of affecting the system they run on)
  • abnormal program terminations (i.e. situations where a program ends unexpectedly and therefore might not get a chance to explicitly free its dynamically allocated memory itself)

任何有价值的操作系统都必须能够应对这种情况.它必须将系统的其他部分(例如自身和其他正在运行的进程)与故障进程隔离开.否则,进程的内存泄漏将传播到系统.这意味着操作系统会泄漏内存(通常被认为是错误).

Any operating system worth its salt has to be able to deal with such situations. It has to isolate other parts of the system (e.g. itself and other running processes) from a faulty process. If it did not, a process' memory leak would propagate to the system. Meaning that the OS would leak memory (which is usually considered a bug).

保护系统免受内存泄漏的一种方法是,确保进程结束后,释放其使用的所有内存(可能还有其他资源).

One way to protect the system from memory leaks is by ensuring that once a process ends, all the memory (and possibly other resources) that it used get freed.

这篇关于堆内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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