C语言开发之内存管理

问题引入

函数exec_func(int* arr, int len)内部申请多个动态数组,当程序执行过程中出现错误时,需要将之前申请的数组全部释放掉,导致代码过于冗长。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int exec_func(int* arr, int len){
    for(int i = 0; i < len; i++){
        arr[i] = 1;
    }
    srand((unsigned)time(NULL));
    int status = 1;
    //申请辅助数组
    int* a = (int*)malloc(sizeof(int) * len);
    //执行一些程序
    //若大于4则表示该部分代码执行失败
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行a\n");
    if(status == 0){
        free(a);
        a = NULL;
        return status;
    }
    float* b = (float*)malloc(sizeof(float) * len);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行b\n");
    if(status == 0){
        free(b);
        b = NULL;
        free(a);
        a = NULL;
        return status;
    }
    double* c = (double*)malloc(sizeof(double) * len);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行c\n");
    if(status == 0){
        free(c);
        c = NULL;
        free(b);
        b = NULL;
        free(a);
        a = NULL;
        return status;
    }
    char* d = (char*)malloc(sizeof(char) * len);
    //执行一些程序
    status = rand() % 10 > 4 ? 1 : 0;
    printf("执行d\n");
    if(status == 0){
        free(d);
        d = NULL;
        free(c);
        c = NULL;
        free(b);
        b = NULL;
        free(a);
        a = NULL;
        return status;
    }
    //后续处理相关的程序
    printf("执行后续\n");
    free(a);
    a = NULL;
    free(b);
    b = NULL;
    free(c);
    c = NULL;
    free(d);
    d = NULL;
    return status;
}

int main(){
    int len = 10;
    int* arr = (int*)malloc(sizeof(int) * 10);
    int status = exec_func(arr, len);
    if(status == 0){
        fprintf(stderr,"执行失败\n");
    }else{
        printf("执行成功\n");
    }
    return 0;
}

方案一

goto语句如下:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int exec_func(int* arr, int len){
    for(int i = 0; i < len; i++){
        arr[i] = 1;
    }
    srand((unsigned)time(NULL));
    int status = 1;
    //申请辅助数组
    int* a = (int*)malloc(sizeof(int) * len);
    //执行一些程序
    //若大于4则表示该部分代码执行失败
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行a\n");
    if(status == 0){
        goto FREEA;
    }
    float* b = (float*)malloc(sizeof(float) * len);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行b\n");
    if(status == 0){
        goto FREEB;
    }
    double* c = (double*)malloc(sizeof(double) * len);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行c\n");
    if(status == 0){
        goto FREEC;
    }
    char* d = (char*)malloc(sizeof(char) * len);
    //执行一些程序
    status = rand() % 10 > 4 ? 1 : 0;
    printf("执行d\n");
    if(status == 0){
        goto FREED;
    }
    //后续处理相关的程序
    printf("执行后续\n");
    FREED: free(d);
    d = NULL;
    FREEC: free(c);
    c = NULL;
    FREEB: free(b);
    b = NULL;
    FREEA: free(a);
    a = NULL;
    return status;
}

int main(){
    int len = 10;
    int* arr = (int*)malloc(sizeof(int) * 10);
    int status = exec_func(arr, len);
    if(status == 0){
        fprintf(stderr,"执行失败\n");
    }else{
        printf("执行成功\n");
    }
    return 0;
}

编译执行

gcc  test_memory.c -o tm
./tm

输出

执行a
执行b
执行c
执行失败

可以看出跳转成功。
goto语句很方便解决上述问题,但是甲方要求禁用goto语句!!!

方案二

与c++中对象的思想一致,将函数中的临时变量存储到结构体struct imitation_class{}中,利用函数指针使相关函数成为结构体struct imitation_class{}的变量,类比对象的构造函数与析构函数,为结构体写初始化函数imitation_class* init_imitation_class()与销毁函数void destory_imitation_class(imitation_class** ic)。初始换函数中初始化动态数组指针为NULL,函数指针指向使用结构体内相关变量的函数,函数执行完毕后,调用析构函数统一释放内存。(注:若存在多个执行函数,考虑到内存问题,可以每执行完一个执行函数调用一次销毁函数。)

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

struct imitation_class{
    int* a;
    float* b;
    double* c;
    char* d;
    int (*__exec_func)(struct imitation_class* ic, int*, int);
};
typedef struct imitation_class imitation_class;

int __exec_func(imitation_class* ic, int* arr, int len){
    for(int i = 0; i < len; i++){
        arr[i] = 1;
    }
    srand((unsigned)time(NULL));
    int status = 1;
    //申请辅助数组
    ic->a = (int*)malloc(sizeof(int) * len);
    //执行一些程序
    //若大于4则表示该部分代码执行失败
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行a\n");
    if(status == 0){
        return status;
    }
    ic->b = (float*)malloc(sizeof(float) * len);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行b\n");
    if(status == 0){
        return status;
    }
    ic->c = (double*)malloc(sizeof(double) * len);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行c\n");
    if(status == 0){
        return status;
    }
    ic->d = (char*)malloc(sizeof(char) * len);
    //执行一些程序
    status = rand() % 10 > 4 ? 1 : 0;
    printf("执行d\n");
    if(status == 0){
        return status;
    }
    //后续处理相关的程序
    printf("执行后续\n");
    return status;
}

imitation_class* init_imitation_class(){
    imitation_class* ic = (imitation_class*)malloc(sizeof(imitation_class));
    ic->a = NULL;
    ic->b = NULL;
    ic->c = NULL;
    ic->d = NULL;
    ic->__exec_func = __exec_func;
    return ic;
}

void destory_imitation_class(imitation_class** ic){
    if(ic == NULL || *ic == NULL){
        return;
    }
    imitation_class* pic = *ic;
    if(pic->a != NULL){
        free(pic->a);
        pic->a = NULL;
    }
    if(pic->b != NULL){
        free(pic->b);
        pic->b = NULL;
    }
    if(pic->c != NULL){
        free(pic->c);
        pic->c = NULL;
    }
    if(pic->d != NULL){
        free(pic->d);
        pic->d = NULL;
    }
    free(pic);
    pic = NULL;
    return;
}

//对外函数
int exec_func(int* arr, int len){
    imitation_class* ic = init_imitation_class();
    int status = ic->__exec_func(ic, arr, len);
    destory_imitation_class(&ic);
    return status;
}

int main(){
    int len = 10;
    int* arr = (int*)malloc(sizeof(int) * 10);
    int status = exec_func(arr, len);
    if(status == 0){
        fprintf(stderr,"执行失败\n");
    }else{
        printf("执行成功\n");
    }
    return 0;
}

编译执行

gcc  test_memory.c -o tm
./tm

输出

```bash
gcc  test_memory.c -o tm
./tm

输出

执行a
执行b
执行c
执行失败

方案二变种

如果函数内的动态变量过多,可以考虑在函数执行前分配一块特别大的buffer,供后续使用。这种方式的缺点也显而易见,如果某些动态变量空间大小需要在执行之后才能确定,不可能提前计算好内存大小。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

struct imitation_class{
    char* buffer;
    int (*__exec_func)(struct imitation_class* ic, int*, int);
};
typedef struct imitation_class imitation_class;

int __exec_func(imitation_class* ic, int* arr, int len){
    //提前计算内存空间
    int len_a = len, len_b = len, len_c = len, len_d = len;
    int total_Byte = sizeof(int) * len_a + sizeof(float) * len_b 
                    + sizeof(double) * len_c + sizeof(char) * len_d;
    ic->buffer = (char*)malloc(total_Byte);
    char* pointer = ic->buffer;
    for(int i = 0; i < len; i++){
        arr[i] = 1;
    }
    srand((unsigned)time(NULL));
    int status = 1;
    //申请辅助数组
    int* a = (int*)pointer;
    pointer = (char*)((int*)pointer + len_a);
    //执行一些程序
    //若大于4则表示该部分代码执行失败
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行a\n");
    if(status == 0){
        return status;
    }
    float* b = (float*)pointer;
    pointer = (char*)((float*)pointer + len_b);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行b\n");
    if(status == 0){
        return status;
    }
    double* c = (double*)pointer;
    pointer = (char*)((float*)pointer + len_c);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行c\n");
    if(status == 0){
        return status;
    }
    char* d = (char*)pointer;
    pointer = (char*)((char*)pointer + len_c);
    //执行一些程序
    status = rand() % 10 > 4 ? 1 : 0;
    printf("执行d\n");
    if(status == 0){
        return status;
    }
    //后续处理相关的程序
    printf("执行后续\n");
    return status;
}

imitation_class* init_imitation_class(){
    imitation_class* ic = (imitation_class*)malloc(sizeof(imitation_class));
    ic->buffer = NULL;
    ic->__exec_func = __exec_func;
    return ic;
}

void destory_imitation_class(imitation_class** ic){
    if(ic == NULL || *ic == NULL){
        return;
    }
    imitation_class* pic = *ic;
    if(pic->buffer != NULL){
        free(pic->buffer);
        pic->buffer = NULL;
    }
    free(pic);
    pic = NULL;
    return;
}

//对外函数
int exec_func(int* arr, int len){
    imitation_class* ic = init_imitation_class();
    int status = ic->__exec_func(ic, arr, len);
    destory_imitation_class(&ic);
    return status;
}

int main(){
    int len = 10;
    int* arr = (int*)malloc(sizeof(int) * 10);
    int status = exec_func(arr, len);
    if(status == 0){
        fprintf(stderr,"执行失败\n");
    }else{
        printf("执行成功\n");
    }
    free(arr);
    return 0;
}

针对已经完成部分的项目而言,需要重新写结构体,初始换函数与销毁函数,再将执行函数拆分为对外函数(int exec_func(int* arr, int len))与内部函数(int __exec_func(int* arr, int len))。但是时间不宽裕,大型项目按照“问题引入"部分写了大半,不想做太多改动,怎么办呢?

方案三

引入内存管理模块!大致思想是将所有申请的内存压入链表栈中,写一个销毁链表的函数统一销毁申请的内存。
见代码:
trash.h
将所有数据类型全部转换为void**,即将动态数组头指针的地址存入value中。如果仅将动态数组头指针存入value,那么内存释放之后无法对改头指针赋值为NULL,可能导致内存释放后使用(主要原因还是释放内存不赋值为NULL不符合甲方编程规范),所以这里选择void**。

#include<stdio.h>
struct trash_node{
    void** value;
    struct trash_node* next;
};
typedef struct trash_node trash_node;

trash_node* create_trash_node();
void trash_push(trash_node* head, void** ele);
void trash_destory(trash_node** head);

trash.c

#include <stdlib.h>
#include <stdio.h>
#include "trash.h"

trash_node* create_trash_node(){
    trash_node* head = (trash_node*)malloc(sizeof(trash_node));
    if(head == NULL){
        return NULL;
    }
    head->next = NULL;
    head->value = NULL;
    return head;
}

void trash_push(trash_node* head, void** ele){
    if(head == NULL || ele == NULL){
        return;
    }
    trash_node* tmp_node = (trash_node*)malloc(sizeof(trash_node));
    if(tmp_node == NULL){
        return;
    }
    tmp_node->value = ele;
    tmp_node->next = head->next;
    head->next = tmp_node;
    return;
}

void trash_destory(trash_node** head){
    if(head == NULL || *head == NULL){
        return;
    }
    trash_node* next_node = *head;
    trash_node* free_node = *head;
    while(next_node != NULL){
        free_node = next_node;
        next_node = next_node->next;
        if(free_node != NULL){
            if(free_node->value != NULL && *(free_node->value) != NULL){
                free(*(free_node->value));
                *(free_node->value) = NULL;
            }
            free_node->value = NULL;
            free(free_node);
            free_node = NULL;
        }
    }
    return;
}

具体使用方式为:
1.在函数开头调用trash_node* create_trash_node()函数,创建内存管理模块头指针。
2.每次申请内存,都将该内存头指针的地址利用函数void trash_push(trash_node* head, void** ele)链接到head中。
3.当遇到程序执行错误需要退出或执行完毕的时候,调用void trash_destory(trash_node** head)函数即可实现对所有已申请内存的释放。
用例代码:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "trash.h"

int exec_func(int* arr, int len){
    trash_node* head = create_trash_node();
    for(int i = 0; i < len; i++){
        arr[i] = 1;
    }
    srand((unsigned)time(NULL));
    int status = 1;
    //申请辅助数组
    int* a = (int*)malloc(sizeof(int) * len);
    trash_push(head, (void**)&a);
    //执行一些程序
    //若大于4则表示该部分代码执行失败
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行a\n");
    if(status == 0){
        trash_destory(&head);
        return status;
    }
    float* b = (float*)malloc(sizeof(float) * len);
    trash_push(head, (void**)&b);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行b\n");
    if(status == 0){
        trash_destory(&head);
        return status;
    }
    double* c = (double*)malloc(sizeof(double) * len);
    trash_push(head, (void**)&c);
    //执行一些程序
    status = rand() % 10 > 3 ? 1 : 0;
    printf("执行c\n");
    if(status == 0){
        trash_destory(&head);
        return status;
    }
    char* d = (char*)malloc(sizeof(char) * len);
    trash_push(head, (void**)&d);
    //执行一些程序
    status = rand() % 10 > 4 ? 1 : 0;
    printf("执行d\n");
    if(status == 0){
        trash_destory(&head);
        return status;
    }
    //后续处理相关的程序
    printf("执行后续\n");
    trash_destory(&head);
    return status;
}

int main(){
    int len = 10;
    int* arr = (int*)malloc(sizeof(int) * 10);
    int status = exec_func(arr, len);
    if(status == 0){
        fprintf(stderr,"执行失败\n");
    }else{
        printf("执行成功\n");
    }
    return 0;
}

编译执行

gcc  test_memory.c -o tm
./tm

输出

```bash
gcc  test_memory.c -o tm
./tm

输出

执行a
执行b
执行c
执行d
执行后续
执行成功

方案三PULS

如果函数中存在申请的空间在函数外仍然需要被使用,但是程序执行过程中出现错误时要被销毁怎么办?设计方案为添加四个标识,分别为SAVE_FOR_OUT(外部需要),TEMP_SPACE(外部不需要),OCCUR_ERROR(程序执行出错)以及EXE_NORMAL(程序正常执行)。
那么在该函数中,存在四种状态如下:

外部是否需要程序是否出错是否完全释放
SAVE_FOR_OUTOCCUR_ERROR
SAVE_FOR_OUTEXE_NORMAL
TEMP_SPACEOCCUR_ERROR
TEMP_SPACEEXE_NORMAL

可以看出,只有当状态为SAVE_FOR_OUT且EXE_NORMAL时不会释放。见代码:
trash.h

#ifndef ML_TRASH_H
#define ML_TRASH_H

#ifdef __cplusplus
extern "C"{
#endif

//在程序结束时不会释放改地址空间
#define SAVE_FOR_OUT 1
//在程序结束时需要全部释放
#define TEMP_SPACE 0
//程序执行出错
#define OCCUR_ERROR 1
//程序正常结束
#define EXE_NORMAL 0

#define trash_push(type, head, ele, _is_save) {                     \
    if(!_trash_push(head, (void**)&(ele), _is_save)){               \
        return (type)0;                                             \
    }                                                               \
}

#define trash_destory(type, head, is_error) {   \
    if(!_trash_destory(&(head), is_error)){     \
        return (type)0;                         \
    }                                           \
}
/**
* \brief 存储动态空间地址的地址,用来对内存进行管理
* \param value 动态空间地址的地址
* \param is_save 执行结束是否释放,仅接受SAVE_FOR_OUT与TEMP_SPACE
* \param next 指向下一个节点
*/
struct trash_node{
    void** value;
    int is_save;
    struct trash_node* next;
};
typedef struct trash_node trash_node;

/**
* \brief create_trash_node 函数,创建垃圾回收头指针
* \return 返回垃圾回收头指针
*/
trash_node* create_trash_node();
/**
* \brief trash_push 记录内存地址的地址
* \param head 垃圾头指针
* \param ele 内存地址的地址
* \return int 正确执行返回1,错误执行返回0
*/
int _trash_push(trash_node* head, void** ele, int _is_save);
/**
* \brief trash_destory 释放记录到head内的动态内存与节点内存
* \param head 垃圾头指针
* \param is_error 程序是否出错,如果出错的话将对所有内存进行释放;
*                 如果正常执行,将仅释放符号is_save = TEMP_SPACE对应的地址空间
*/
int _trash_destory(trash_node** head, int is_error);

#ifdef __cplusplus
}
#endif

#endif

trash.c

#include <stdlib.h>
#include <stdio.h>
#include "trash.h"

trash_node* create_trash_node(){
    trash_node* head = (trash_node*)malloc(sizeof(trash_node));
    if(head == NULL){
        return NULL;
    }
    head->next = NULL;
    head->value = NULL;
    return head;
}

int _trash_push(trash_node* head, void** ele, int _is_save){
    if(head == NULL || ele == NULL){
        return 0;
    }
    if(_is_save != SAVE_FOR_OUT && _is_save != TEMP_SPACE){
        return 0;
    }
    trash_node* tmp_node = (trash_node*)malloc(sizeof(trash_node));
    if(tmp_node == NULL){
        _trash_destory(&head, OCCUR_ERROR);
        return 0;
    }
    tmp_node->value = ele;
    tmp_node->is_save = _is_save;
    tmp_node->next = head->next;
    head->next = tmp_node;
    return 1;
}

int _trash_destory(trash_node** head, int is_error){
    if(head == NULL || *head == NULL){
        return 0;
    }
    if(is_error != OCCUR_ERROR && is_error != EXE_NORMAL){
        return 0;
    }
    trash_node* next_node = *head;
    trash_node* free_node = *head;
    while(next_node != NULL){
        free_node = next_node;
        next_node = next_node->next;
        if(free_node != NULL){
            //绘制is_error与is_save状态表可以看到,当is_error >= is_save时所有内存必须释放
            if(is_error >= free_node->is_save && free_node->value != NULL && *(free_node->value) != NULL){
                free(*(free_node->value));
                *(free_node->value) = NULL;
            }
            free_node->value = NULL;
            free(free_node);
            free_node = NULL;
        }
    }
    return 1;
}

test_memory.c

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "trash.h"

int* exec_func(int* arr, int len){
    trash_node* head = create_trash_node();
    for(int i = 0; i < len; i++){
        arr[i] = 1;
    }
    srand((unsigned)time(NULL));
    int status = 1;
    //申请辅助数组
    int* a = (int*)malloc(sizeof(int) * len);
    for(int i = 0; i < len; i++){
        a[i] = arr[i];
    }
    trash_push(int*, head, a, SAVE_FOR_OUT);
    //执行一些程序
    //若大于1则表示该部分代码执行失败
    status = rand() % 10 > 1 ? 1 : 0;
    printf("执行a\n");
    if(status == 0){
        trash_destory(int*, head, OCCUR_ERROR);
        return NULL;
    }
    float* b = (float*)malloc(sizeof(float) * len);
    trash_push(int*, head, b, TEMP_SPACE);
    //执行一些程序
    status = rand() % 10 > 1 ? 1 : 0;
    printf("执行b\n");
    if(status == 0){
        trash_destory(int*, head, OCCUR_ERROR);
        return NULL;
    }
    double* c = (double*)malloc(sizeof(double) * len);
    trash_push(int*, head, c, TEMP_SPACE);
    //执行一些程序
    status = rand() % 10 > 1 ? 1 : 0;
    printf("执行c\n");
    if(status == 0){
        trash_destory(int*, head, OCCUR_ERROR);
        return NULL;
    }
    char* d = (char*)malloc(sizeof(char) * len);
    trash_push(int*, head, d, TEMP_SPACE);
    //执行一些程序
    status = rand() % 10 > 1 ? 1 : 0;
    printf("执行d\n");
    if(status == 0){
        trash_destory(int*, head, OCCUR_ERROR);
        return NULL;
    }
    //后续处理相关的程序
    printf("执行后续\n");
    trash_destory(int*, head, EXE_NORMAL);
    return a;
}

int main(){
    int len = 10;
    int* arr = (int*)malloc(sizeof(int) * 10);
    int* a = exec_func(arr, len);
    if(a == NULL){
        fprintf(stderr,"main执行失败\n");
    }else{
        for(int i = 0; i < len; i++){
            printf("%d, ", a[i]);
        }
        printf("\n");
        free(a);
    }
    free(arr);
    return 0;
}

编译执行

执行a
执行b
执行c
执行d
执行后续
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值