?
このドキュメントでは、 php中國(guó)語(yǔ)ネットマニュアル リリース
在頭文件<stdlib.h>中定義 | ||
---|---|---|
void * malloc(size_t size); |
分配size
未初始化存儲(chǔ)的字節(jié)。
如果分配成功,則返回一個(gè)指向已分配內(nèi)存塊中適用于任何對(duì)象類(lèi)型的最低(第一個(gè))字節(jié)的指針。
如果size
為零,則行為是實(shí)現(xiàn)定義的(可能會(huì)返回空指針,或者可能會(huì)返回一些可能不用于訪問(wèn)存儲(chǔ)但必須傳遞到的非空指針free
)。
malloc是線程安全的:它的行為好像只訪問(wèn)通過(guò)參數(shù)可見(jiàn)的內(nèi)存位置,而不是任何靜態(tài)存儲(chǔ)。先前調(diào)用free或realloc來(lái)釋放內(nèi)存區(qū)域的同步 - 調(diào)用malloc來(lái)分配相同或相同內(nèi)存區(qū)域的一部分。這種同步發(fā)生在解除分配函數(shù)對(duì)內(nèi)存的任何訪問(wèn)之后,以及malloc訪問(wèn)內(nèi)存之前。所有分配和解除分配功能在內(nèi)存的每個(gè)特定區(qū)域都有一個(gè)總的順序。 | (自C11以來(lái)) |
---|
尺寸 | - | 要分配的字節(jié)數(shù) |
---|
成功時(shí),將指針?lè)祷氐叫路峙涞膬?nèi)存的開(kāi)始位置。返回的指針必須用free()
或來(lái)解除分配realloc()
。
失敗時(shí),返回一個(gè)空指針。
#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標(biāo)準(zhǔn)(ISO / IEC 9899:2011):
7.22.3.4 malloc函數(shù)(p:349)
C99標(biāo)準(zhǔn)(ISO / IEC 9899:1999):
7.20.3.3 malloc函數(shù)(p:314)
C89 / C90標(biāo)準(zhǔn)(ISO / IEC 9899:1990):
4.10.3.3 malloc函數(shù)