C語言動態(tài)內存管理介紹
更新時間:2021年12月31日 09:10:30 作者:心在南
大家好,本篇文章主要講的是C語言動態(tài)內存管理介紹,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
前言:
簡單記錄一下,內存管理函數(shù)
為什么使用動態(tài)內存呢?
簡單理解就是可以最大限度調用內存
用多少生成多少,不用時就釋放而靜止內存不能釋放
動態(tài)可避免運行大程序導致內存溢出
C 語言為內存的分配和管理提供了幾個函數(shù):
頭文件:<stdlib.h>
注意:void * 類型表示未確定類型的指針?
1.malloc() 用法
?分配一塊大小為 num 的內存空間
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[12]; char *test; strcpy(name, "KiKiNiNi"); // 動態(tài)分配內存 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 memory\n"); } else { strcpy(test, "Maybe just like that!"); } printf("Name = %s\n", name); printf("Test: %s\n", test); return 0; } // 運行結果 // Name = KiKiNiNi // Test: Maybe just like that!
2.calloc() 用法
?分配 num 個長度為 size 的連續(xù)空間
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[12]; char *test; strcpy(name, "KiKiNiNi"); // 動態(tài)分配內存 test = (void *) calloc(26, sizeof(char)); // (void *) calloc(int num, int size) -> num = 26 / size = sizeof(char) // void * 表示 未確定類型的指針 // 分配了 num 個 大小為 size 的連續(xù)空間 存放值初始化為 0 if (test == NULL) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy(test, "Maybe just like that!"); } printf("Name = %s\n", name); printf("Test: %s\n", test); return 0; } // 運行結果 // Name = KiKiNiNi // Test: Maybe just like that!
3.realloc() 與 free() 用法
重新調整內存的大小和釋放內存
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[12]; char *test; strcpy(name, "KiKiNiNi"); // 動態(tài)分配內存 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 memory\n"); } else { strcpy(test, "Maybe just like that!"); } /* 假設您想要存儲更大的描述信息 */ test = (char *) realloc(test, 100 * sizeof(char)); if (test == NULL) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcat(test, " It's a habit to love her."); } printf("Name = %s\n", name); printf("Test: %s\n", test); // 釋放 test 內存空間 free(test); return 0; } // 運行結果 // Name = KiKiNiNi // Test: Maybe just like that! It's a habit to love her.
到此這篇關于C語言動態(tài)內存管理介紹的文章就介紹到這了,更多相關C語言動態(tài)內存內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++ 數(shù)據(jù)結構鏈表的實現(xiàn)代碼
這篇文章主要介紹了C++ 數(shù)據(jù)結構鏈表的實現(xiàn)代碼的相關資料,需要的朋友可以參考下2017-01-01