1 一次性分配较大内存,free如何获知该内存大小并完全释放,实现机制是?
2 如下代码:
int *p = (int*)malloc(sizeof(int));
free((char*)p);
什么情况下会出现内存泄漏?
3 <c prime>
一书一个版本在高级数据结构一节中写过如下代码:
while(p != NULL){
free(p);
p = p->next;
}
这样的用法是否永远可行?
伊谢尔伦2017-04-17 11:18:14
char*
is smaller than int*
due to integer truncation, problems will occur (not as simple as a memory leak). But I can’t seem to find a system in which these two pointers have different sizes, right? ringa_lee2017-04-17 11:18:14
The answers to 1 and 3 are very clear, let me add the second point:
In the C language standard library, the free function prototype is:
void free (void* ptr);
In the C language standard, void* and all pointers to various data are consistent with char*, including size and alignment.
So there is no problem in performing various conversions between data pointers.
But please note: The C language standard does not stipulate that data pointers and function pointers are the same. This is undefined behavior.
大家讲道理2017-04-17 11:18:14
The memory block allocated by malloc() contains a header block
, which is used to record information such as the size of the allocated memory. free() will read this block and release the memory.
Allocate int type memory size, but only release half of the space (assume int is 2 bytes here), so when the excess memory continues to increase and fills up the memory space, it will cause a memory leak.
This release method is wrong. Are you sure this is what is written in the book? The correct way to write it should be:
for(p = head; p != NULL; p = q){
q = p->next;
free(p);
}