天天看點

C語言進階:第38課、動态記憶體配置設定

動态記憶體配置設定的意義:

C語言中的一切操作都是基于記憶體的

變量和數組等都是記憶體的别名

記憶體配置設定由編譯器在編譯期間決定

定義數組的時候必須指定數組長度

數組長度是在編譯期就必須确定的

需求:程式運作過程中,可能需要使用一些額外的記憶體空間

malloc 和 free 用于執行動态記憶體配置設定和釋放

malloc所配置設定的是一塊連續的記憶體

malloc以位元組為機關,并且不帶任何的類型資訊

free用于将動态記憶體歸還系統

void* malloc(size_t size);  //void*指針,說明是不帶任何類型資訊
		void free(void* pointer);
           
C語言進階:第38課、動态記憶體配置設定

malloc和free是庫函數,而不是系統調用。

malloc實際配置設定的記憶體可能會比請求的多(空閑的記憶體池空間分布不同)。

不能依賴于不同平台下的malloc行為(為了移植性)。

當請求的動态記憶體無法滿足時,malloc傳回NULL。(是以在進行malloc申請後,要進行判斷記憶體申請是否成功)

當free的參數為NULL時,函數直接傳回。

malloc(0); 将傳回什麼呢?

動态記憶體申請有兩個概念:一個是起始位址,一個是長度;

此處申請是成功的,得到了一個起始位址,但是長度為0。

不斷地申請malloc(0)不free(),會造成記憶體洩漏嗎?

    答案是會!因為malloc(0)有可能會得到4個位元組的記憶體,是以不斷地申請,不free()的話,肯定會出現記憶體洩漏。

記憶體洩漏檢測子產品:(必讀)

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

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

#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));  //通過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;
}
           

編譯運作(注意不同平台下的編譯效果):

~/will$ gcc test.c
~/will$ ./a.out
pI[0] = 0, pS[0] = 0        //pI的值也是0,這是因為Linux下的特殊情況,在Windows(BCC)下,這個值是不确定的。
pI[1] = 0, pS[1] = 0
pI[2] = 0, pS[2] = 0
pI[3] = 0, pS[3] = 0
pI[4] = 0, pS[4] = 0
Before: pI = 0x970b008
After: pI =  0x970b030    //新申請一段記憶體,将原先的記憶體釋放
pI[0] = 0       //重置後的pI的值也是0,,在Windows(BCC、VS)下,這個值也是不确定的。
pI[1] = 0
pI[2] = 0
pI[3] = 0
pI[4] = 0
pI[5] = 0
pI[6] = 0
pI[7] = 0
pI[8] = 0
pI[9] = 0
           

小結:

動态記憶體配置設定是C語言中的強大功能

程式 能夠在需要的時候有機會使用更多的記憶體

malloc單純的從系統中申請 【固定位元組大小】的記憶體

calloc能以類型大小為機關申請記憶體并 初始化為0

realloc用于重置記憶體大小, 擴大部分的内容是随機值。