C语言进阶课程学习记录-第38课 - 动态内存分配
- 内存动态分配
- 实验-malloc(0)
- 实验
- 实验-realloc和calloc
- 小结
本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
内存动态分配
实验-malloc(0)
#include <stdio.h>
#include <malloc.h>
int main()
{
int i = 0;
int* pI = (int*)malloc(0 * sizeof(int));
printf("pI=%p\n", pI);
free(pI);
return 0;
}
/*
output:
pI=00032D08
*/
实验
#define MALLOC(n) mallocEx(n, __FILE__, __LINE__)
#define FREE(p) freeEx(p)
void* mallocEx(size_t n, const char* file, const line);//扩展malloc
void freeEx(void* p);
void PRINT_LEAK_INFO();
#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);
}
}
}
#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;
}
/*
output:
Potential Memory Leak Info:
Address: 00A52D40, size:100, Location: D:\Users\cy\Cxuexi\Test\test1.c:6
*/
实验-realloc和calloc
#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;
}
/*
output:
pI[0] = 14488680, pS[0] = 0
pI[1] = 14494984, pS[1] = 0
pI[2] = 0, pS[2] = 0
pI[3] = 0, pS[3] = 0
pI[4] = 0, pS[4] = 0
Before: pI = 00DD2D28
After: pI = 00DD1468
pI[0] = 14488680
pI[1] = 14494984
pI[2] = 0
pI[3] = 0
pI[4] = 0
pI[5] = 673215333
pI[6] = 691419256
pI[7] = 1667845468
pI[8] = 1869836146
pI[9] = 1394635878
*/
小结
动态内存分配是C语言中的强大功能
程序能够在需要的时候有机会使用更多的内存
malloc单纯的从系统中申请固定字节大小的内存
calloc能以类型大小为单位申请内存并初始化为0
realloc用于重置内存大小