malloc,calloc,realloc的区别

void *malloc(size_t size);

void *calloc(size_t nmemb, size_t size);

void *realloc(void *ptr, size_t size);


malloc

  The  malloc()  function allocates size bytes and returns a pointer to the allocated memory.  The memory is not initialized.  If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

calloc

The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory.   The  memory is set to zero.  If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

realloc

The realloc() function changes the size of the memory block pointed to by ptr to size bytes.  The contents will be unchanged in the  range  from  the  start  of the region up to the minimum of the old and new sizes.  If the new size is larger than the old size, the added memory will not be initialized.  If ptr is NULL, then the call is equivalent to malloc(size), for all values of size;  if  size  is  equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).  Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().  If the area pointed to was  moved,  a  free(ptr)  is done.


malloc和calloc的区别

实际上,任何事物都有两面性,有好的一面,必然存在不好的地方。这就是效率。calloc函数由于给每一个空间都要初始化值,那必然效率较malloc要低,并且现实世界,很多情况的空间申请是不需要初始值的,这也就是为什么许多初学者更多的接触malloc函数的原因。

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

int main(){
        //calloc会将分配的内存初始化
        int *p = (int *)calloc(5,sizeof(int));
        //如果malloc分配的内存已经被分配使用过,打印出来的可能是各种各样的值,不会被初始化
        int *pp = (int *)malloc(5*sizeof(int));
        int size = 5,num =0;
        for(num = 0;num < size;num++){
                printf("%d %p,",*(p+num),p);
        }
        printf("\n");
        for(num = 0;num<size;num++){
                printf("%d %p,",*(pp+num),pp);
        }
        printf("\n");
        return 0;
}

realloc

realloc是从堆上分配内存的.当扩大一块内存空间时,realloc()试图直接从堆上现存的数据后面的那些字节中获得附加的字节,如果能够满足,自然天下太平;如果数据后面的字节不够,问题就出来了,那么就使用堆上第一个有足够大小的自由块,现存的数据然后就被拷贝至新的位置,而老块则放回到堆上.这句话传递的一个重要的信息就是数据可能被移动

#include<stdio.h>
#include<stdlib.h>
int main(){
        int *p = (int *)malloc(20*sizeof(int));
        int *pp = (int *)realloc(p,50000*sizeof(int));
        printf("p = %p, pp = %p\n",p,pp);
        printf("p = %d, pp = %d\n",sizeof(p),sizeof(pp));
        free(pp);
        //free(pp);
        return 0;
}


[bigdata@ssecbigdata06 day08]$ ./malloc
p = 0x70b010, pp = 0x7f099afaa010
p = 8, pp = 8 














猜你喜欢

转载自blog.csdn.net/czj1992czj/article/details/79877700