动态内存管理 malloc calloc realloc

malloc(size_t size):向内存空间申请指定大小的内存,并把该申请的内存以指针的形式返回

#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
    int a;
    char* b;
};
int main()
{
    struct S* ps = malloc(sizeof(struct S));//申请结构体大小的内存,并把结构体指针指向该内存
    printf("%d\n",sizeof(struct S));//8个字节
    ps->a = 100;//通过指针给成员赋值
    ps->b = "hello word";
    printf("%s\n",ps->b);
    printf("%p\n",ps);//打印指针指向的地址,也就是结构体的起始地址
    printf("%p\n",ps->b);
    printf("%p\n",&(ps->a));//打印成员a的地址,显示就是结构体的起始地址


    return 0;

}

cmalloc(size,size_t):向内存申请size_t个,size大小的内存空间,它会把这段内存空间全部初始化为0,然后以指针的形式返回该地址.

#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
    int a;
    char* b;
};
int main()
{
    struct S* ps = calloc(sizeof(struct S),2);//申请2个结构体大小的内存空间,16字节
    printf("%d\n",sizeof(struct S));//8字节
    ps->a = 100;
    ps->b = "hello word";
    printf("%s\n",ps->b);
    printf("%p\n",ps);
    printf("%p\n",ps->b);
    printf("%p\n",&(ps->a));
    free(ps);//释放内存


    return 0;

}

 最上面16个字节,全部为零

realloc():给已经申请的内存,重新定义大小,并返回一个新的指针,这个指针有可能和原指针相同,取决于再次申请内存的大小.如果是一个新的指针,它会把前面指针对应的数据全部复制到新的内存里面.

#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
    int a;
    char* b;
};
int main()
{
    struct S* ps = calloc(sizeof(struct S),2);
    struct s* ptr = realloc(ps,24);
    printf("%d\n",sizeof(struct S));
    ps->a = 100;
    ps->b = "hello word";
    printf("%s\n",ps->b);
    printf("%p\n",ps);
    printf("%p\n",ps->b);
    printf("%p\n",&(ps->a));


    return 0;

}

 两个指针相同,只是在PS的后面加了8个字节

#include <stdio.h>
#include <stdlib.h>
#define MAX(X,Y) (X>Y?X:Y)
#include <math.h>
struct S
{
    int a;
    char* b;
};
int main()
{
    struct S* ps = calloc(sizeof(struct S),2);
    struct s* ptr = realloc(ps,240000);//把申请内存加大到一定程度
    printf("%d\n",sizeof(struct S));
    ps->a = 100;
    ps->b = "hello word";
    printf("%s\n",ps->b);
    printf("%p\n",ps);
    printf("%p\n",ps->b);
    printf("%p\n",&(ps->a));


    return 0;

}

 这里两个指针就不相同了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值