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;
}

猜你喜欢

转载自blog.csdn.net/zhixingheyi_tian/article/details/84750623