malloc的使用

据说,calloc会自动清零,而malloc不会,但是我没看出来..

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

typedef struct {
 
            int x;
 
            int y;
}Point;



int main(void)
{
 
    Point*p=NULL;
 
    p=(Point*)malloc(sizeof(Point)*60);
 
    inti=0;
 
    for(i=0;i<60;i++){
 
          printf("P[%d].x=%d\t",i,p[i].x);
 
          printf("P[%d].y=%d\t",i,p[i].y);
 
    }
 
    printf("\n");

 
    return0;
}

2:

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

typedef struct {
 
            int x;
 
            int y;
}Point;



int main(void)
{
 
    Point*p=NULL;
 
    p=(Point*)calloc(60,sizeof(Point));
 
    inti=0;
 
    for(i=0;i<60;i++){
 
          printf("P[%d].x=%d\t",i,p[i].x);
 
          printf("P[%d].y=%d\t",i,p[i].y);
 
    }
 
    printf("\n");

 
    return0;
}

结果是一样的...

3:

对malloc的一点实验:

#include <stdio.h>
#include <stdlib.h>
void *checkmemalloc(unsigned int size){
 
void* p;
 
p=malloc(size);
 
if(p==NULL){
 
    fprintf(stderr,"error memalloc failed!\n");
 
    exit(1);
 
}
 
return p;
}

int main(int argc,char** argv)
{
 

 
int *p1=NULL,*p2=NULL;
 
if(argc<3){
 
    fprintf(stderr,"error input.\n");
 
    exit(2);
 
}
 
p1=checkmemalloc(atoi(argv[1]));
 
printf("p1 is %p\n",p1);
 
free(p1);
 
p2=checkmemalloc(atoi(argv[2]));
 
printf("p2 is %p\n",p2);
 
free(p2);
 

 
return 0;
}


如果释放了p1,那么p2是否会使用p1使用过的那部分内存...
答案是不确定...看来堆内存的管理和垃圾收集算法有关了...
而不是简单的申请和释放
ly@linux-t0jw:~/桌面> ./ch 1000000 2
p1 is 0xb748a008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 100 2
p1 is 0x804b008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 100 50
p1 is 0x804b008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 100 100
p1 is 0x804b008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 100 10000
p1 is 0x804b008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 100 1000000
p1 is 0x804b008
p2 is 0xb74c4008
ly@linux-t0jw:~/桌面> ./ch 1 1
p1 is 0x804b008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 10 10
p1 is 0x804b008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 1 2000
p1 is 0x804b008
p2 is 0x804b008
ly@linux-t0jw:~/桌面> ./ch 1000000000 1
p1 is 0x7bc5b008
p2 is 0x804b008

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值