代码这么可爱的吗??(malloc与calloc的区别)

   **#include 
   void *malloc(size_t size);
   void free(void *ptr);
   void *calloc(size_t nmemb, size_t size);
   void *realloc(void *ptr, size_t size);**
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().

       The **free()** function frees the memory space pointed  to  by  ptr,  which
       must  have  been  returned  by a previous call to malloc(), calloc() or
       realloc().  Otherwise, or if free(ptr) has already been called  before,
       undefined behavior occurs.  If ptr is NULL, no operation is performed.

       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().**

       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 mal‐
       loc(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(),  cal‐
       loc()  or  realloc().  If the area pointed to was moved, a free(ptr) is
       done.

malloc()和calloc()的功能都是在内存的动态存储区中分配n个长度为size的连续空间,函数返回一个指向分配起始地址的指针。

而他们之间的区别就是calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不初始化,里边数据是随机的垃圾数据。比如说在内存中分配长度为10的int类型的数组,若使用的是函数calloc(),则数组被初始化为10个0,若是使用malloc()函数,则数组里面存的是垃圾数据。

扩展资料:

malloc()在内存中分配内存的工作机制:

malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表。

调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块。

然后,将该内存块一分为二(一块的大小与用户请求的大小相等,另一块的大小就是剩下的字节)。

接下来,将分配给用户的那块内存传给用户,并将剩下的那块(如果有的话)返回到连接表上。调用free函数时,它将用户释放的内存块连接到空闲链上。

到最后,空闲链会被切成很多的小内存片段,如果这时用户申请一个大的内存片段,那么空闲链上可能没有可以满足用户要求的片段了。

于是,malloc函数请求延时,并开始在空闲链上翻箱倒柜地(原来代码也可以这么可爱)检查各内存片段,对它们进行整理,将相邻的小空闲块合并成较大的内存块。

如果无法获得符合要求的内存块,malloc函数会返回NULL指针,因此在调用malloc动态申请内存块时,一定要进行返回值的判断。

来自于百度!!!

你可能感兴趣的:(Study)