动态内存分配

动态内存分配

C语言中一切操作都是基于内存的

变量和数组都是内存的别名

内存分配由编译器在编译期决定

定义数组的时候必须指定数组长度

数组长度是在编译器就必须确定的


程序在运行的过程中,可能会使用一些额外的内存空间,需要通过malloc 和 free

malloc所分配的是一块连续内存,以字节为单位,并且不带任何的类型信息

malloc实际分配的内存可能会比请求的多

当动态内存无法满足是malloc返回NULL

当free参数为NULL时,函数直接返回

malloc(0); 也会返回一个地址

检测内存泄漏模块

#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 int line);
void freeEx(void* p);
void PRINT_LEAK_INFO();

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

其他动态申请内存函数


void* calloc(size_t num,size_t size);  //calloc 会将返回的内存初始化为0
    short* pS = (short*)calloc1sizeof(short));
void* realloc(void* pointer,size_t new_size); //用于修改原先已经分配的内存大小,当第一个参数为NULL时,等价于malloc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值