11.7 Summary
When an array is declared, its size must be known at compile time. Dynamic allocation allows a program to create space for an array whose size isnʹt known until runtime.
當數組被聲明時,必須在編譯時知道它的長度。動态記憶體配置設定允許程式為一個長度在運作時才知道的數組配置設定記憶體空間。
The malloc and calloc functions both allocate memory and return a pointer to it. The argument to malloc is the number of bytes of memory needed. In contrast,calloc requires the number of elements you want and the size of each element. calloc initializes the memory to zero before returning, whereas malloc leaves the memory uninitialized. The realloc function is called to change the size of an existing block of dynamically allocated memory. Increases in size may be accomplished by copying the data from the existing block to a new, larger block. When a dynamically allocated block is no longer needed, free is called to return it to the pool of available memory.Memory must not be accessed after it has been freed.
malloc 和calloc 函數都用于動态配置設定一塊記憶體,并傳回一個指向該塊記憶體的指針。malloc 的參數就是需要配置設定的記憶體的位元組數。和它不同的是, calloc 的參數是你需要配置設定的元素個數和每個元素的長度。calloc 函數在傳回前把記憶體初始化為零,而malloc 函數傳回時記憶體并未以任何方式進行初始化。調用realloc 函數可以改變一塊已經動态配置設定的記憶體的大小。增加記憶體塊大小時有可能采取的方法是把原來記憶體塊上的所有資料複制到一個新的、更大的記憶體塊上。當一個動态配置設定的記憶體塊不再使用時,應該調用free 函數把它歸還給可用記憶體池。記憶體被釋放之後便不能再被通路。
The pointer returned by malloc, calloc, and realloc will be NULL if the requested allocation could not be performed. Erroneously accessing memory outside of an allocated block may cause the same errors as accessing memory outside of an array, but can also corrupt the pool of available memory and lead to a program failure.You may not pass a pointer to free that was not obtained from an earlier call to malloc,calloc, or realloc. Nor may you free a portion of a block.
如果請求的記憶體配置設定失敗, malloc 、calloc 和realloc 函數傳回的将是一個NULL 指針。錯誤地通路配置設定記憶體之外的區域所引起的後果類似越界通路一個數組,但這個錯誤還可能破壞可用記憶體池,導緻程式失敗。如果一個指針不是從早先的malloc 、calloc 或realloc 函數傳回的,它是不能作為參數傳遞給free 函數的。你也不能隻釋放一塊記憶體的一部分。
A memory leak is memory that has been dynamically allocated but has not been freed and is no longer in use. Memory leaks increase the size of the program,and may lead to a crash of the program or the system.
記憶體洩漏是指記憶體被動态配置設定以後,當它不再使用時未被釋放。記憶體洩漏會增加程式的體積,有可能導緻程式或系統的崩潰。