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.

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 at some point of time, system cannot allocate 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);

C++相关问答推荐

__VA_OPT__(,)是否可以检测后面没有任何内容的尾随逗号?

为什么I2C会发送错误的数据?

向上强制转换C中的数值类型总是可逆的吗?

如何识别Linux中USB集线器(根)和连接到集线器(根设备)的设备(子设备)?

X64:并发写入布尔数组

用C++从外部ELF符号读取值

GTK函数调用将完全不相关的char* 值搞乱

如何在C-函数中混合使用C代码和ASM?

添加函数会 destruct 嵌入式C代码(无IDE)

如何确保我将使用C标准库函数的函数版本,如&getc";,而不是类似函数的宏版本?

为什么这个分配做得不好呢?

C";中的ANN运行时判断失败#2-变量outputLayer;周围的堆栈已损坏.运行后出错

Realloc():中止的下一个大小无效(核心转储)

为什么我的旧式&q;函数在传递浮点数时会打印2?

I';我试着从.txt文件中读取文本,并用c计算其中的单词数量

在哪里可以找到叮当返回码的含义?

DennisM.Ritchie的C编程语言一书中关于二进制搜索的代码出现错误?

System V 消息队列由于某种原因定期重置

为什么这里的符号没有解析?

K&R 练习 1-24