C语言的内存管理——动态内存分配

本文来自狄泰软件学院——《C语言深度剖析课程》

动态内存分配的意义

  1. C语言中的一切操作都是基于内存的
  2. 变量和数组都是内存的别名
  3. 内存分配由编译器在编译期间决定
  4. 定义数组的时候必须指定数组长度
  5. 数组长度是在编译器就必须确定的

需求:程序运行的过程中,可能需要使用一些额外的内存空间

malloc和free

malloc和free用于执行动态内存分配和释放

这里写图片描述

  1. malloc所分配的是一块连续的内存
  2. malloc以字节为单位,并且不带任何类型信息
  3. free用于将动态内存归还系统
    • void* malloc(size_t size);
    • void free(void* pointer);
  4. malloc和free是库函数,而不是系统调用
  5. malloc实际分配的内存可能会比请求的多
  6. 不能依赖于不同平台下的malloc行为
  7. 当请求的动态内存无法满足时,malloc返回NULL
  8. 当free的参数为NULL时,函数直接返回。

思考:malloc(0);将返回什么?

示例代码:内存泄露检测模块

/* --------- main.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.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);
        }
    }
}

/* --------- 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

输出结果:
Potential Memory Leak Info:
Address: 0x85ed018, size:100, Location: 38-1.c:6

calloc和relloc

malloc的同胞兄弟

 void* calloc(size_t num, size_t size);
 void* realloc(void* pointer, size_t new_size);
  1. calloc的参数代表所返回内存的类型信息
  2. calloc会将返回的内存初始化为0
  3. realloc用于修改一个原先已经分配的内存块大小
  4. 在使用realloc之后应该使用其返回值
  5. 当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] = 0, pS[0] = 0
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 = 0x8b0d008
After: pI = 0x8b0d030
pI[0] = 0
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

猜你喜欢

转载自blog.csdn.net/small_prince_/article/details/80604066