發(fā)布于:2021-02-05 11:35:20
0
230
0
什么是C中的free()函數(shù)?
C庫中的free()函數(shù)允許您釋放或取消分配先前由calloc(),malloc()或realloc()函數(shù)分配的內存塊。它釋放內存塊,并將內存返回堆。它有助于釋放程序中的內存,以供以后使用。
在C語言中,變量的內存在編譯時自動釋放。對于C中的動態(tài)內存分配,您必須顯式地取消分配內存。如果未完成,則可能會遇到內存不足錯誤。
語法
void free(void *ptr)
這里,ptr是需要釋放的內存塊。
例如:
#includeint main() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
*(ptr + 2) = 50;
printf("Value of the 2nd integer is %d",*(ptr + 2));
}
free(ptr);
}
輸出
Value of the 2nd integer is 50