文字
分享

在头文件<stdlib.h>中定义



void * malloc(size_t size);



分配size未初始化存储的字节。

如果分配成功,则返回一个指向已分配内存块中适用于任何对象类型的最低(第一个)字节的指针。

如果size为零,则行为是实现定义的(可能会返回空指针,或者可能会返回一些可能不用于访问存储但必须传递到的非空指针free)。

malloc是线程安全的:它的行为好像只访问通过参数可见的内存位置,而不是任何静态存储。先前调用free或realloc来释放内存区域的同步 - 调用malloc来分配相同或相同内存区域的一部分。这种同步发生在解除分配函数对内存的任何访问之后,以及malloc访问内存之前。所有分配和解除分配功能在内存的每个特定区域都有一个总的顺序。

(自C11以来)

参数

尺寸

-

要分配的字节数

返回值

成功时,将指针返回到新分配的内存的开始位置。返回的指针必须用free()或来解除分配realloc()

失败时,返回一个空指针。

#include <stdio.h>   #include <stdlib.h> 
 int main(void) {
    int *p1 = malloc(4*sizeof(int));  // allocates enough for an array of 4 int
    int *p2 = malloc(sizeof(int[4])); // same, naming the type directly
    int *p3 = malloc(4*sizeof *p3);   // same, without repeating the type name 
    if(p1) {        for(int n=0; n<4; ++n) // populate the array
            p1[n] = n*n;        for(int n=0; n<4; ++n) // print it back out            printf("p1[%d] == %d\n", n, p1[n]);    } 
    free(p1);    free(p2);    free(p3);}

输出:

p1[0] == 0p1[1] == 1p1[2] == 4p1[3] == 9

参考

  • C11标准(ISO / IEC 9899:2011):

    • 7.22.3.4 malloc函数(p:349)

  • C99标准(ISO / IEC 9899:1999):

    • 7.20.3.3 malloc函数(p:314)

  • C89 / C90标准(ISO / IEC 9899:1990):

    • 4.10.3.3 malloc函数