动态内存管理

动态内存管理

malloc、free

//
// Created by a1073 on 2019/7/4.
//

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

int main(void) {
    int *ptr;
    ptr = (int *)malloc(sizeof(int));
    if (ptr == NULL){
        printf("分配内存失败");
        exit(1);
    }
    printf("请输入一个整数\n");
    scanf("%d", ptr);
    printf("您输入的整数为%d\n", *ptr);
    free(ptr);
    printf("您输入的整数为%d\n", *ptr);
    /*
     *您输入的整数为13905232
     *释放后的空间存在,但变为非法空间(不可将变量的取址给其赋值)*/		
    return 0;

}

对动态申请的空间是存放在堆上,务必注意使用完后释放内存!
free释放的空间仅可以malloc calloc realloc申请的空间

内存泄漏

  1. 隐式内存泄漏(即用完内存块没有及时使用free函数释放)
  2. 丢失内存块地址(例如,ptr = &num,ptr中的地址变为常量的地址,不能进行释放)

malloc申请任意大小的空间

//
// Created by a1073 on 2019/7/4.
//

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

int main(void) {
    int *ptr = NULL;
    int num;
    printf("请输入需要待录入数据的个数:");
    scanf("%d", &num);
    ptr = (int *)malloc(sizeof(int) * num);
    for (int i = 0; i < num; ++i) {
        printf("请录入第%d数:", i + 1);
        scanf("%d", &ptr[i]);
    }
    printf("您录入的数据是:\n");
    // 因为申请的是连续空间,所以用数组来索引数据
    for (int j = 0; j < num; ++j) {
        printf("%d ", ptr[j]);
    }
    return 0;
}

malloc、calloc

//
// Created by a1073 on 2019/7/5.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10

int main(void) {
    int *ptr = NULL;
    ptr = (int *)malloc(sizeof(int) * N);
    if (ptr == NULL){
        printf("分配内存失败!\n");
        exit(1);
    }
    memset(ptr, 0, N * sizeof(int));
    /*
     * ptr = (int *)calloc(N, sizeof(int));
     * 上一行代码等价于如下
     * ptr = (int *)malloc(sizeof(int) * N);
     * memset(ptr, 0, N * sizeof(int));*/
    for (int i = 0; i < N; ++i) {
        printf("ptr[%d] = %d\n", i, ptr[i]);
    }
    free(ptr);
    return 0;
}

realloc

//
// Created by a1073 on 2019/7/5.
//

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

int main(void) {
    int num, count = 0;
    int *ptr = NULL;
    do{
       printf("请输入一个整数(输入-1结束):");
       scanf("%d", &num);
       count++;
       ptr = (int *)realloc(ptr, count * sizeof(int));
       if(ptr == NULL){
           exit(1);
       }
       ptr[count - 1] = num;
    }while (num != -1);

    for (int i = 0; i < count; ++i) {
        printf("ptr[%d] = %d\n", i, ptr[i]);
    }
    free(ptr);
    ptr = NULL;
    return 0;
}

注意:新分配的空间如果比原来的大,数据不会发生丢失;如果新分配的空间比原来小,数据会丢失,慎用!

如果ptr的值为null,则realloc相当于malloc
如果size的参数为0,则realloc相当于free
realloc的参数ptr只能为NULL,或者是realloc malloc calloc返回的指针类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值