动态内存分配
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*)calloc(1,sizeof(short));
void* realloc(void* pointer,size_t new_size); //用于修改原先已经分配的内存大小,当第一个参数为NULL时,等价于malloc