【C】 38_動態內存分配

動態內存分配的意義

  • C 語言中的一切操做都是基於內存的
  • 變量和數組都是內存的別名編程

    • 內存分配由編譯器在編譯期間決定
    • 定義數組的時候必須指定數組長度
    • 數組長度是在編譯期就必須肯定的

需求:數組

程序運行的過程當中,可能須要使用一些額外的內存空間

malloc 和 free

  • malloc 和 free 用於執行動態內存分配和釋放

clipboard.png

  • malloc 所分配的是一塊連續的內存
  • malloc 以字節爲單位,而且不帶任何的類型信息
  • free 用於將動態內存歸還系統

void* malloc(size_t size);
void free(void* pointer);多線程

注意事項

  • malloc 和 free 是庫函數,而不是系統調用
  • malloc 實際分配的內存可能會比請求的多
  • 不能依賴於不一樣平臺下的 malloc 行爲
  • 當請求的動態內存沒法知足時 malloc 返回 NULL
  • 當 free 的參數爲 NULL 時,函數直接返回

malloc 是庫函數,不一樣的操做系統對內存的管理多是是不一樣的。例,操做系統爲了高效,內存池中空閒內存老是爲4字節整數倍。當經過malloc函數動態申請3字節,存在可能實際分配爲4字節。函數

這形成malloc實際分配的內存可能請求的多。同時,爲了提升程序的能夠移植性,不能依賴於不一樣平臺下的malloc行爲。spa

思考

  • malloc(0); 將返回什麼?
#include <stdio.h>
#include <malloc.h>

int main()
{
    int* p = (int*)malloc(0);
    
    printf("%p\n", p);
}
輸出:【無警告,無錯誤】
0x9616008

發生了什麼?操作系統

內存地址實質包含兩個含義:內存首地址 + 內存長度。
malloc(0) 申請成功,返回申請內存首地址,只不過內存長度爲0。
  • 當不停得 malloc(0), 而不free,最終得可執行程序可能會產生內存泄漏嗎?

會。
由於malloc申請獲得的內存空間每每比實際申請得大。現代操做系統通常會4字節對齊,將致使malloc(0, 1, 2, 3) 均可能得到得實際內存空間爲4。而不是0,1,2,3,這將致使內存泄漏。所以,malloc 和 free 必須成對出現。線程

示例分析: 內存泄漏檢測模塊

mleak.hcode

#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.cip

#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 int 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);
        }
    }
}

main.c內存

#include <stdio.h>
#include "mleak.h"

void f()
{
    MALLOC(100);
}

int main()
{
    int* p1 = (int*)MALLOC(3 * sizeof(int));
    int* p2 = (int*)MALLOC(3 * sizeof(int));
    
    f();
    
    p1[0] = 1;
    p1[1] = 2;
    p1[2] = 3;
    
    FREE(p1);
    
    PRINT_LEAK_INFO();
    
    return 0;
}
輸出:
Address: 0x97a8018, size:12, Location: test.c:12
Address: 0x97a8028, size:100, Location: test.c:6

注意:以上文件沒有作臨界資源保護(多線程編程),在實際項目中須要進行再擴展。

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;
}
輸出:
pI[0] = -842150451, pS[0] = 0
pI[1] = -842150451, pS[1] = 0
pI[2] = -842150451, pS[2] = 0
pI[3] = -842150451, pS[3] = 0
pI[4] = -842150451, pS[4] = 0
Before: pI = 01136DB0
After: pI = 01136DB0
pI[0] = -842150451
pI[1] = -842150451
pI[2] = -842150451
pI[3] = -842150451
pI[4] = -842150451
pI[5] = -842150451
pI[6] = -842150451
pI[7] = -842150451
pI[8] = -842150451
pI[9] = -842150451

分析:
pI, mallo申請內存中的值爲隨機值
pI, realloc以後,指向的地址將發生改變。擴大以後的部分爲隨機值,重合的部分爲原始值

小結

  • 動態內存分配是 C 語言中的強大功能
  • 程序可以在須要的時候有機會使用更多的內存
  • malloc 單純的從系統中申請固定字節大小的內存,而不進行初始化
  • calloc 能以類型大小爲單位申請內存並初始化爲0
  • realloc 用於重置內存大小

以上內容參考狄泰軟件學院系列課程,請你們保護原創!

相關文章
相關標籤/搜索