我是靠谱客的博主 单薄发箍,这篇文章主要介绍C语言动态内存管理介绍,现在分享给大家,希望可以做个参考。

前言:

简单记录一下,内存管理函数

为什么使用动态内存呢?
简单理解就是可以最大限度调用内存
用多少生成多少,不用时就释放而静止内存不能释放
动态可避免运行大程序导致内存溢出

C 语言为内存的分配和管理提供了几个函数:

头文件:<stdlib.h>

注意:void * 类型表示未确定类型的指针 

1.malloc() 用法

 分配一块大小为 num 的内存空间

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[12]; char *test; strcpy(name, "KiKiNiNi"); // 动态分配内存 test = (char *) malloc(26 * sizeof(char)); // (void *) malloc(int num) -> num = 26 * sizeof(char) // void * 表示 未确定类型的指针 // 分配了一块内存空间 大小为 num 存放值是未知的 if (test == NULL) { fprintf(stderr, "Error - unable to allocate required memoryn"); } else { strcpy(test, "Maybe just like that!"); } printf("Name = %sn", name); printf("Test: %sn", test); return 0; } // 运行结果 // Name = KiKiNiNi // Test: Maybe just like that!

2.calloc() 用法

 分配 num 个长度为 size 的连续空间

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[12]; char *test; strcpy(name, "KiKiNiNi"); // 动态分配内存 test = (void *) calloc(26, sizeof(char)); // (void *) calloc(int num, int size) -> num = 26 / size = sizeof(char) // void * 表示 未确定类型的指针 // 分配了 num 个 大小为 size 的连续空间 存放值初始化为 0 if (test == NULL) { fprintf(stderr, "Error - unable to allocate required memoryn"); } else { strcpy(test, "Maybe just like that!"); } printf("Name = %sn", name); printf("Test: %sn", test); return 0; } // 运行结果 // Name = KiKiNiNi // Test: Maybe just like that!

3.realloc() 与 free() 用法

重新调整内存的大小和释放内存

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[12]; char *test; strcpy(name, "KiKiNiNi"); // 动态分配内存 test = (char *) malloc(26 * sizeof(char)); // (void *) malloc(int num) -> num = 26 * sizeof(char) // void * 表示 未确定类型的指针 // 分配了一块内存空间 大小为 num 存放值是未知的 if (test == NULL) { fprintf(stderr, "Error - unable to allocate required memoryn"); } else { strcpy(test, "Maybe just like that!"); } /* 假设您想要存储更大的描述信息 */ test = (char *) realloc(test, 100 * sizeof(char)); if (test == NULL) { fprintf(stderr, "Error - unable to allocate required memoryn"); } else { strcat(test, " It's a habit to love her."); } printf("Name = %sn", name); printf("Test: %sn", test); // 释放 test 内存空间 free(test); return 0; } // 运行结果 // Name = KiKiNiNi // Test: Maybe just like that! It's a habit to love her.

到此这篇关于C语言动态内存管理介绍的文章就介绍到这了,更多相关C语言动态内存内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是单薄发箍最近收集整理的关于C语言动态内存管理介绍的全部内容,更多相关C语言动态内存管理介绍内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(160)

评论列表共有 0 条评论

立即
投稿
返回
顶部