Dynamic memory allocation C

//使用动态分配内存时,要包含头文件<stdlib.h>
	//malloc的参数为要分配的内存的字节数
	//其返回所分配内存的第一个字节的地址
	//返回类型是void*,但实际中常常转换为具体类型便于使用
	//如果因某种原因而不能分配将返回NULL指针,所以使用时应验证是否分配成功
	int *pNumber1=(int *)malloc(100*sizeof(int));
	
	//calloc把内存分配为给定大小的数组,并初始化分配的内存为0
	//calloc需要两个参数,1为数组元素个数,2为数组元素占用的字节数
	//其他和malloc类似
	int *pNumber2=(int *)calloc(100,sizeof(int));
	
	//释放上面分配的内存
	//	free(pNumber1);
	free(pNumber2);

	//重新分配内存,需要保证之前的没释放
	//参数1是指针,即前面分配返回的地址
	//参数2为要分配的新内存的字节数,其字节数不应超过之前的字节数
	//否则与以前的内存区域大小相同
	//realloc会释放之前分配的内存,然后进行重新分配
	realloc(pNumber1,80*sizeof(int));


Use the basic rules for dynamic allocation of memory:

1, to avoid the large number of small blocks of memory allocated. Allocated heap memory has some overhead, so to allocate large blocks of memory than many small allocation of a few large blocks of memory overhead.

2, allocate memory only when needed. Used up immediately release it.

3, always ensure the release of allocated memory. When writing code to allocate memory, it is necessary to determine where the release of the code in memory.

4, prior to the release of memory, ensure you do not accidentally overwrite memory addresses allocated on the heap, otherwise the program will be a memory leak. When allocating memory in a loop, to be especially careful.

Reproduced in: https: //my.oschina.net/secyaher/blog/274411

Guess you like

Origin blog.csdn.net/weixin_34038293/article/details/91967119