1. 程式人生 > >malloc and free

malloc and free

void *malloc(size_t size);

void* 表示未確定型別的指標,void *可以指向任何型別的資料,更明確的說是指申請記憶體空間時還不知道使用者是用這段空間來儲存什麼型別的資料(比如是char還是int或者其他資料型別)。

void free(void *ptr);

與malloc()函式配對使用,釋放malloc函式申請的動態記憶體。(另:對於free§這句語句,如果p 是NULL 指標,那麼free 對p 無論操作多少次都不會出問題。如果p 不是NULL 指標,那麼free 對p連續操作兩次就會導致程式執行錯誤。)

sample

#include <string.h>
#include <stdio.h>
#include <alloc.h> //or #include <malloc.h>
int main(void)
{
	char *str;
	/* allocate memory for string */
	str = (char *)malloc(10);
	/* copy "Hello" to string */
	strcpy(str, "Hello");
	/* display string */
	printf("String is %s\n", str);
	/* free memory */
	free(str);
	str=NULL;
	return 0;
}