程序运行过程中,可能需要使用一些额外内存空间,
通过malloc向操作系统申请内存,满足额外的内存空间。
malloc所分配的是一块连续的的内存,它以字节为单位,并且不带任何的类型信息。
free用于动态内存归还系统。
Malloc 申请的内存一般比自己想要的多,不同平台下结果是不一样的
一个嵌入式上面开发的案列:
malloc是库函数,在嵌入式设备直接在里面修改当malloc无法满足是返回NULL这样的行为,主动使系统复位重启(因为一旦嵌入式设备没有可用的内存,意味着嵌入式设备没法工作了,这样处理保证设备)。
问题:
malloc(0); // 将返回什么?
内存其实包含如下概念:
1.内存起始地址
2.申请的长度
如果申请malloc(0),是可以使用的,但是没法用,因为申请的只是一个地址而没有长度,这样系统就没法用。 但是一直申请malloc(0) 不释放也会内存泄露,因为实际的内存是别申请的要多。
内存泄露检测模块的函数(抽象出来的模型)
//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, int line);
void freeEx(p);
void Print_Leak_Info();
#endif
// mleak.c 文件
#include "leak.h"
#define SIZE 256
typedef struct
{
void* pointer;
int size;
const char* file;
int line;
}MemST;
static MemST g_record[SIZE];
void* mallocEx(size_t n, const char* file, 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(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;
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 );
}
}
}
// main.c 文件
int main()
{
int* p = (int*)MALLOC(sizeof(int));
return 0;
}
在linux下结果如下:
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;
}