C語言動態(tài)內(nèi)存管理介紹
前言:
簡單記錄一下,內(nèi)存管理函數(shù)
為什么使用動態(tài)內(nèi)存呢?
簡單理解就是可以最大限度調(diào)用內(nèi)存
用多少生成多少,不用時就釋放而靜止內(nèi)存不能釋放
動態(tài)可避免運行大程序?qū)е聝?nèi)存溢出
C 語言為內(nèi)存的分配和管理提供了幾個函數(shù):
頭文件:<stdlib.h>

注意:void * 類型表示未確定類型的指針?
1.malloc() 用法
?分配一塊大小為 num 的內(nèi)存空間
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[12];
char *test;
strcpy(name, "KiKiNiNi");
// 動態(tài)分配內(nèi)存
test = (char *) malloc(26 * sizeof(char));
// (void *) malloc(int num) -> num = 26 * sizeof(char)
// void * 表示 未確定類型的指針
// 分配了一塊內(nèi)存空間 大小為 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;
}
// 運行結(jié)果
// 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)分配內(nè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;
}
// 運行結(jié)果
// Name = KiKiNiNi
// Test: Maybe just like that!
3.realloc() 與 free() 用法
重新調(diào)整內(nèi)存的大小和釋放內(nèi)存
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[12];
char *test;
strcpy(name, "KiKiNiNi");
// 動態(tài)分配內(nèi)存
test = (char *) malloc(26 * sizeof(char));
// (void *) malloc(int num) -> num = 26 * sizeof(char)
// void * 表示 未確定類型的指針
// 分配了一塊內(nèi)存空間 大小為 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 內(nèi)存空間
free(test);
return 0;
}
// 運行結(jié)果
// Name = KiKiNiNi
// Test: Maybe just like that! It's a habit to love her.
到此這篇關(guān)于C語言動態(tài)內(nèi)存管理介紹的文章就介紹到這了,更多相關(guān)C語言動態(tài)內(nèi)存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于嘗試開發(fā)PHP的MYSQL擴展的使用
本篇文章小編將為大家介紹,關(guān)于嘗試開發(fā)PHP的MYSQL擴展的使用,需要的朋友可以參考一下2013-04-04
C++ 數(shù)據(jù)結(jié)構(gòu)鏈表的實現(xiàn)代碼
這篇文章主要介紹了C++ 數(shù)據(jù)結(jié)構(gòu)鏈表的實現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-01-01

