網站首頁 編程語言 正文
一、動態內存分配的意義
C語言中的一切操作都是基于內存的
變量和數組都是內存的別名
- 內存分配由編譯器在編譯期間決定
- 定義數組的時候必須指定數組長度
- 數組長度是在編譯期就必須確定的
需求:程序運行的過程中,可能需要使用一些額外的內存空間
二、malloc 和 free
malloc 和 free 用于執行動態內存分配和釋放
- malloc 所分配的是一塊連續的內存
- malloc 以字節為單位,并且不帶任何的類型信息
- free 用于將動態內存歸還系統
void* malloc(size_t size);
void free(void* pointer);
注意事項
- malloc 和 free 是庫函數,而不是系統調用
- malloc 實際分配的內存可能會比請求的多
- 不能依賴于不同平臺下的 malloc 行為
- 當請求的動態內存無法滿足時 malloc 返回 NULL
- 當 free 的參數為 NULL 時,函數直接返回
下面看一個內存泄漏檢測模塊的示例:
test.c:
#include <stdio.h> #include "mleak.h" void f() { MALLOC(100); } int main() { int* p = (int*)MALLOC(3 * sizeof(int)); f(); p[0] = 1; p[1] = 2; p[2] = 3; FREE(p); PRINT_LEAK_INFO(); return 0; }
mleak.h:
#ifndef _MLEAK_H_ #define _MLEAK_H_ #include <malloc.h> #define MALLOC(n) mallocEx(n, __FILE__, __LINE__) #define FREE(p) freeEx(p) void* mallocEx(size_t n, const char* file, const line); void freeEx(void* p); void PRINT_LEAK_INFO(); #endif
mleak.c:
#include "mleak.h" #define SIZE 256 /* 動態內存申請參數結構體 */ typedef struct { void* pointer; int size; const char* file; int line; } MItem; static MItem g_record[SIZE]; /* 記錄動態內存申請的操作 */ void* mallocEx(size_t n, const char* file, const line) { void* ret = malloc(n); /* 動態內存申請 */ if( ret != NULL ) { int i = 0; /* 遍歷全局數組,記錄此次操作 */ for(i = 0; i < SIZE; i++) { /* 查找位置 */ if( g_record[i].pointer == NULL ) { g_record[i].pointer = ret; g_record[i].size = n; g_record[i].file = file; g_record[i].line = line; break; } } } return ret; } void freeEx(void* p) { if( p != NULL ) { int i = 0; /* 遍歷全局數組,釋放內存空間,并清除操作記錄 */ for(i = 0; i < SIZE; i++) { if( g_record[i].pointer == p ) { g_record[i].pointer = NULL; g_record[i].size = 0; g_record[i].file = NULL; g_record[i].line = 0; free(p); break; } } } } void PRINT_LEAK_INFO() { int i = 0; printf("Potential Memory Leak Info:\n"); /* 遍歷全局數組,打印未釋放的空間記錄 */ for(i = 0; i < SIZE; i++) { if( g_record[i].pointer != NULL ) { printf("Address: %p, size:%d, Location: %s:%d\n", g_record[i].pointer, g_record[i].size, g_record[i].file, g_record[i].line); } } }
輸出結果如下, 因為 MALLOC(100); 之后沒有進行釋放內存,所以被檢查出來了。
暫時不能用于工程開發,需要再開發才行。因為 malloc 往往在不同的線程中被調用,因此 malloc 函數必須要有互斥的操作。因為 static MItem g_record[SIZE]; 這個靜態全局數組是一種臨界區,必須被保護起來。
三、關于 malloc(0)
malloc(0);
將返回什么?
下面看一段代碼:
#include <stdio.h> #include <malloc.h> int main() { int* p = (int*) malloc(0); printf("p = %p\n", p); free(p); return 0; }
輸出結果如下:?
這說明 malloc(0) 是合法的,內存地址其實包含兩個概念,一個是內存的起始地址,一個是內存的長度。在平常我們可能會只注意內存的首地址,對于長度卻忽略了。malloc(0) 在這個程序中申請到的內存起始地址為?0x82c3008,長度為 0。
但是我們在程序里不停寫 malloc(0),會造成內存泄漏嗎?答案是肯定的,因為malloc 實際分配的內存可能會比請求的多,目前的操作系統一般都是 4 字節對齊的,所以寫 malloc(0) 系統實際返回的字節數也許就是 4 字節。
四、calloc 和 realloc
malloc 的同胞兄弟
void* calloc(size_t num, size_t size);
void* realloc(void* pointer, size_t new_size);
calloc 的參數代表所返回內存的類型信息
- calloc 會將返回的內存初始化為 0
realloc 用于修改一個原先已經分配的內存塊大小
- 在使用 realloc 之后應該使用其返回值
- 當 pointer 的第一個參數為 NULL 時,等價于 malloc
下面看一個 calloc 和 realloc 的使用示例:
#include <stdio.h> #include <malloc.h> #define SIZE 5 int main() { int i = 0; int* pI = (int*)malloc(SIZE * sizeof(int)); short* pS = (short*)calloc(SIZE, sizeof(short)); for(i = 0; i < SIZE; i++) { printf("pI[%d] = %d, pS[%d] = %d\n", i, pI[i], i, pS[i]); } printf("Before: pI = %p\n", pI); pI = (int*)realloc(pI, 2 * SIZE * sizeof(int)); printf("After: pI = %p\n", pI); for(i = 0; i < 10; i++) { printf("pI[%d] = %d\n", i, pI[i]); } free(pI); free(pS); return 0; }
輸出結果如下:?
malloc 只負責申請空間,不負責初始化,這里的?pI 指針保存的值均為 0 只是巧合罷了,另外使用 realloc 重置之后,內存地址也會改變,pI 指針保存的值也會改變,這里都為 0 同樣也是巧合。
五、小結
- 動態內存分配是 C 語言中的強大功能
- 程序能夠在需要的時候有機會使用更多的內存
- malloc 單純的從系統中申請固定字節大小的內存
- calloc 能以類型大小為單位申請內存并初始化為0
- realloc 用于重置內存大小
原文鏈接:https://blog.csdn.net/weixin_43129713/article/details/124035850
相關推薦
- 2022-11-29 詳解Go語言設計模式之單例模式_Golang
- 2023-06-18 C#實現不同窗體之間傳遞參數_C#教程
- 2021-12-02 深入了解c語言的循環語句_C 語言
- 2023-03-29 golang?channel讀取數據的幾種情況_Golang
- 2022-06-12 Python多線程的使用詳情_python
- 2022-05-23 ZooKeeper分布式協調服務設計核心概念及安裝配置_zabbix
- 2022-03-19 MongoDB數據庫授權認證的實現_MongoDB
- 2022-12-10 React實現控制減少useContext導致非必要的渲染詳解_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支