交流
商城
MCN
登入
注册
首页
提问
分享
讨论
建议
公告
动态
发表新帖
发表新帖
c语言第6章:内存管理
分享
未结
0
685
李延
LV6
2022-05-23
悬赏:20积分
# 1 说明 简单封装malloc 方法,对于内存分配异常时,抛出异常。 # 2 mem.h ```c #ifndef MEM_INCLUDED #define MEM_INCLUDED #include "../except/except.h" extern Exception Mem_Failed; extern void *mem_alloc(long nbytes, const char *file, int line); extern void *mem_calloc(long count,long nbytes,const char *file,int line); extern void mem_free(void *ptr,const char *file,int line); extern void mem_resize(void *ptr,long count,const char *file,int line); #define ALLOC(nbytes) \ mem_alloc(nbytes,__FILE__,__LINE__) #define CALLOC(count,nbytes) \ mem_calloc(count,nbytes,__FILE__,__LINE__) #define FREE(ptr) \ mem_free(ptr,__FILE__,__LINE__) #define RESIZE(ptr,count) \ mem_resize(ptr,count,__FILE__,__LINE__) #define NEW(p) ((p) = ALLOC((long) sizeof *(p))) #define NEW0(p) ((p) = CALLOC(1,(long) sizeof *(p))) #endif ``` # 3 mem.c ```c #include "mem.h" #include "stdlib.h" Exception Mem_Failed = {"Allocation Failed"}; static void throw_error(Exception *exception, const char *file, int line) { if (file == NULL) { Throw(&Mem_Failed); } else { throwFunction(&Mem_Failed, file, line); } } void *mem_alloc(long nbytes, const char *file, int line) { void *ptr; assert(nbytes > 0); ptr = malloc(nbytes); if (ptr == NULL) { throw_error(&Mem_Failed, file, line); } return ptr; } void *mem_calloc(long count, long nbytes, const char *file, int line) { assert(count >0); assert(nbytes >0); void *ptr = calloc(count, nbytes); if(ptr == NULL){ throwFunction(&Mem_Failed, file, line); } return ptr; } void mem_free(void *ptr,const char *file,int line){ if(ptr){ free(ptr); } } void mem_resize(void *ptr,long count,const char *file,int line){ assert(ptr); assert(count >0); ptr = realloc(ptr,count); if(ptr == NULL){ throwFunction(&Mem_Failed, file, line); } } ``` # 4 测试 ```c #include "../mem/mem.h" #include "stdio.h" int main() { int *p; NEW(p); *p = 3; printf("%d\n", *p); FREE(p); printf("%d\n", *p); } ```
回帖
消灭零回复
提交回复
热议榜
java 相关知识分享
8
好的程序员与不好的程序员
6
写给工程师的十条精进原则
5
spring boot以jar包运行配置的logback日志文件没生成
5
一步一步分析SpringBoot启动源码(一)
5
MockMvc测试
5
【吐槽向】是不是有个吐槽的板块比较好玩
4
logstash jdbc同步mysql多表数据到elasticsearch
3
IntelliJ IDEA 优质License Server
3
.gitignore忽略规则
3
SpringBoot启动源码分析
3
一步一步分析SpringBoot启动源码(三)
3
2
一步一步分析SpringBoot启动源码(二)
2
积分不够将无法发表新帖
2
官方产品
Meta-Boot - 基于MCN
MCN - 快速构建SpringBoot应用
微信扫码关注公众号