日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

C語言深入探索動態(tài)內(nèi)存分配的使用_C 語言

作者:清風自在?流水潺潺 ? 更新時間: 2022-06-17 編程語言

一、動態(tài)內(nèi)存分配的意義

C語言中的一切操作都是基于內(nèi)存的

變量和數(shù)組都是內(nèi)存的別名

  • 內(nèi)存分配由編譯器在編譯期間決定
  • 定義數(shù)組的時候必須指定數(shù)組長度
  • 數(shù)組長度是在編譯期就必須確定的

需求:程序運行的過程中,可能需要使用一些額外的內(nèi)存空間

二、malloc 和 free

malloc 和 free 用于執(zhí)行動態(tài)內(nèi)存分配和釋放

  • malloc 所分配的是一塊連續(xù)的內(nèi)存
  • malloc 以字節(jié)為單位,并且不帶任何的類型信息
  • free 用于將動態(tài)內(nèi)存歸還系統(tǒng)

void* malloc(size_t size);

void free(void* pointer);

注意事項

  • malloc 和 free 是庫函數(shù),而不是系統(tǒng)調(diào)用
  • malloc 實際分配的內(nèi)存可能會比請求的多
  • 不能依賴于不同平臺下的 malloc 行為
  • 當請求的動態(tài)內(nèi)存無法滿足時 malloc 返回 NULL
  • 當 free 的參數(shù)為 NULL 時,函數(shù)直接返回

下面看一個內(nèi)存泄漏檢測模塊的示例:

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
 
 
/* 動態(tài)內(nèi)存申請參數(shù)結構體 */
 
typedef struct
{
    void* pointer;
    int size;
    const char* file;
    int line;
 
} MItem;
 
static MItem g_record[SIZE]; /* 記錄動態(tài)內(nèi)存申請的操作 */
 
void* mallocEx(size_t n, const char* file, const line)
{
    void* ret = malloc(n); /* 動態(tài)內(nèi)存申請 */   
 
    if( ret != NULL )
    {
        int i = 0;       
 
        /* 遍歷全局數(shù)組,記錄此次操作 */
 
        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;        
 
        /* 遍歷全局數(shù)組,釋放內(nèi)存空間,并清除操作記錄 */
 
        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");    
 
    /* 遍歷全局數(shù)組,打印未釋放的空間記錄 */
 
    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); 之后沒有進行釋放內(nèi)存,所以被檢查出來了。

暫時不能用于工程開發(fā),需要再開發(fā)才行。因為 malloc 往往在不同的線程中被調(diào)用,因此 malloc 函數(shù)必須要有互斥的操作。因為 static MItem g_record[SIZE]; 這個靜態(tài)全局數(shù)組是一種臨界區(qū),必須被保護起來。

三、關于 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) 是合法的,內(nèi)存地址其實包含兩個概念,一個是內(nèi)存的起始地址,一個是內(nèi)存的長度。在平常我們可能會只注意內(nèi)存的首地址,對于長度卻忽略了。malloc(0) 在這個程序中申請到的內(nèi)存起始地址為?0x82c3008,長度為 0。

但是我們在程序里不停寫 malloc(0),會造成內(nèi)存泄漏嗎?答案是肯定的,因為malloc 實際分配的內(nèi)存可能會比請求的多,目前的操作系統(tǒng)一般都是 4 字節(jié)對齊的,所以寫 malloc(0) 系統(tǒng)實際返回的字節(jié)數(shù)也許就是 4 字節(jié)。

四、calloc 和 realloc

malloc 的同胞兄弟

void* calloc(size_t num, size_t size);

void* realloc(void* pointer, size_t new_size);

calloc 的參數(shù)代表所返回內(nèi)存的類型信息

  • calloc 會將返回的內(nèi)存初始化為 0

realloc 用于修改一個原先已經(jīng)分配的內(nèi)存塊大小

  • 在使用 realloc 之后應該使用其返回值
  • 當 pointer 的第一個參數(shù)為 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 重置之后,內(nèi)存地址也會改變,pI 指針保存的值也會改變,這里都為 0 同樣也是巧合。

五、小結

  • 動態(tài)內(nèi)存分配是 C 語言中的強大功能
  • 程序能夠在需要的時候有機會使用更多的內(nèi)存
  • malloc 單純的從系統(tǒng)中申請固定字節(jié)大小的內(nèi)存
  • calloc 能以類型大小為單位申請內(nèi)存并初始化為0
  • realloc 用于重置內(nèi)存大小

原文鏈接:https://blog.csdn.net/weixin_43129713/article/details/124035850

欄目分類
最近更新