内存分配如何工作以及何时发生?

How does memory allocation work and when does it happen?

我是 C++ 的新手,我想了解内存分配。我想知道内存是在 运行 时间分配还是在代码编译后分配,当 运行 时间开始时,我的操作系统已经知道我需要 X 内存来 运行该程序。如果内存是在 运行 时间内分配的,那么最后使用 delete 释放为动态变量分配的内存有什么意义呢?因为程序将结束并且所有内存都将被释放。

内存在运行时分配。编译器不可能查看您的代码并始终知道需要多少内存,因此每当您调用 new 或 malloc 时,它都必须从操作系统请求那么多字节。

您必须释放内存的原因很简单,因为计算机上的内存是有限的,您不应该使用超过需要的内存。如果您使用的数量超过机器上可用的数量,您将无法再分配更多。

I need to know if the memory is allocated during runtime or after the code gets compiled...

它在运行时,因此得名 动态

...and when runtime starts, my operating system will already know that I need x memory to run the program...

不,内存是在运行时分配的,系统无法知道在编译时需要多少,同样,因此得名dynamic

If the memory is allocated during runtime what is the point to free the memory allocated for dynamic variable using delete at the end... because the program will end and all the memory will already bee freed.

在一个小的示例程序中,您经常会在执行结束时看到delete,这只是说明性的,当然当程序执行结束时,内存无论如何都会被释放。

但是你必须记住,正常的程序比较大。分配和释放内存,程序将继续 运行,其中一些会持续很长时间,如果没有内存管理,在某些时候事情可能会出错。