C语言进阶:第38课、动态内存分配

动态内存分配的意义:

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

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

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

malloc所分配的是一块连续的内存
malloc以字节为单位,并且不带任何的类型信息
free用于将动态内存归还系统

		void* malloc(size_t size);  //void*指针,说明是不带任何类型信息
		void free(void* pointer);

malloc和free是库函数,而不是系统调用。
malloc实际分配的内存可能会比请求的多(空闲的内存池空间分布不同)。
不能依赖于不同平台下的malloc行为(为了移植性)。
当请求的动态内存无法满足时,malloc返回NULL。(所以在进行malloc申请后,要进行判断内存申请是否成功)
当free的参数为NULL时,函数直接返回。

malloc(0); 将返回什么呢?

动态内存申请有两个概念:一个是起始地址一个是长度;

此处申请是成功的,得到了一个起始地址,但是长度为0。

不断地申请malloc(0)不free(),会造成内存泄漏吗?

    答案是会!因为malloc(0)有可能会得到4个字节的内存,所以不断地申请,不free()的话,肯定会出现内存泄漏。

内存泄漏检测模块:(必读)

扫描二维码关注公众号,回复: 2337084 查看本文章
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用于重置内存大小, 扩大部分的内容是随机值。


猜你喜欢

转载自blog.csdn.net/qq_28388835/article/details/80412337
今日推荐