calloc函数的使用和对内存free的认识

  #include<stdlib.h> 

  void *calloc(size_t n, size_t size);

  free();

  目前的理解:  n是多少个这样的size,这样的使用类似有fread,fwrite. 这个函数把内存里面的数据清空了, free确实把本来的buf清空了,buf之后的数据是随机数据,有个问题就是free之后指针没有设置为NULL

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	// calloc   1920
	char* buf = (char*)calloc(1920,sizeof(char));
	if (buf == NULL)
	{
		printf("calloc 分配内存失败\n");
		return -1;
	}
	printf("buf is %d\n", buf[0]);
	printf("buf is %p\n", buf);
	buf[0] = 1;
	printf("buf is %d\n", buf[0]);
	free(buf);
	printf("buf is %p\n",buf);
	printf("buf is %d\n",buf[0]);
	buf = NULL;
	printf("buf is %p\n",buf);
	while (1)
	{
		//printf("buf is %p\n", buf);
	}
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/nowroot/p/12155565.html