c++ - c中free函数的一些问题探讨
天蓬老师
天蓬老师 2017-04-17 11:16:14
0
3
500

1 一次性分配较大内存,free如何获知该内存大小并完全释放,实现机制是?

2 如下代码:

int *p = (int*)malloc(sizeof(int));
free((char*)p);

什么情况下会出现内存泄漏?

3 <c prime>一书一个版本在高级数据结构一节中写过如下代码:

while(p != NULL){
    free(p);
    p = p->next;
}

这样的用法是否永远可行?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
伊谢尔伦
  1. (glibc's) malloc and other functions will record the starting location and size of each memory block when allocating
  2. I see you added the C++ tag, but the question seems to be only about C. In C language, the type of the return value of malloc is generally not converted. Normally there is no problem. When the size of 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?
  3. Never feasible because it is logically wrong. 1. Another thread can use the memory block before you access it; 2. The memory allocator can clear the released memory for safety reasons; 3. Other situations.
左手右手慢动作

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.

大家讲道理
  1. 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.

  2. 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.

  3. 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);
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template