> For the complete documentation index, see [llms.txt](https://fashaun.gitbook.io/dev-c/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://fashaun.gitbook.io/dev-c/pointer/memory-allocation.md).

# Memory Allocation

\#Memory Allocation

**可以用的工具 :**

malloc - 配置不初始化

free - 釋放

calloc - 配置並含初始化

realloc - 改變配置 (resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc)

* Return
  * null : realloc() fail
  * a pointer

**配置但不初始值**

配置一個`int`需要的空間，並傳回該空間的位址，所以使用指標`ptr`來儲存

int \*ptr = malloc(sizeof(int));

**動態配置陣列**

int \*arr = malloc(1000\*sizof(int));

int \*arr = calloc(1000\*sizof(int)); //初始值為0

**重新配置要注意的**

int \*arr1 = malloc(1000\*sizof(int));

int \*arr2 = realloc(arr1,1000\*sizof(int));

arr1 與 arr2 的位址相同並不保證，realloc() 會需要複製資料來改變記憶體的大小，若原位址有足夠的空間，則使用原位址調整記憶體的大小，若空間不足，則重新尋找足夠的空間來進行配置，在這個情況下，realloc() 前舊位址的空間會被釋放掉，因此，必須使用 realloc() 傳回的新位址，而不該使用舊位址，若 realloc() 失敗，則傳回空指標（null）。最好是進行檢查：
