静态内存分配和动态内存分配的区别 [英] Difference between static memory allocation and dynamic memory allocation

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

问题描述

我想知道什么是静态内存分配和动态内存分配的区别?

I would like to know what is the difference between static memory allocation and dynamic memory allocation?

您可以与任何实际的例子解释一下吗?

Could you explain this with any example?

推荐答案

有三种类型的配置 - 静态的,自动的,动态

There are three types of allocation — static, automatic, and dynamic.

静态分配的意思,该程序启动时为你的变量分配内存。在创建程序时的尺寸是固定的。它适用于全局变量,文件作用域变量和变量与静态在函数内部定义的合格。

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

自动分配内存的出现对内部函数定义(非静态)变量,通常存储在的的(尽管C标准并不要求一个堆栈时)。你不必保留使用它们的额外存储器,但在另一方面,也有在这个存储器的寿命有限的控制。例如:在函数中自动变量只有在那里,直到该函数完成

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

void func() {
    int i; /* `i` only exists during `func` */
}

动态内存分配的是一个有点不同。你现在控制的确切大小和这些存储单元的寿命。如果不释放它,你会遇到内存泄漏,这可能会导致应用程序崩溃,因为它在某些时候不能分配更多的内存。

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since it, at some point cannot allocation more memory.

int* func() {
    int* mem = malloc(1024);
    return mem;
}

int* mem = func(); /* still accessible */

在上例中,分配的内存仍然是有效的和可访问的,即使功能终止。当你在内存中完成,你必须释放它:

In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:

free(mem);

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

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