问题描述
如果这是一个愚蠢的问题,我道歉。我只是好奇...是
有任何理由为什么free()在给出之后没有将指针(传递给
)设置为NULL内存回到堆?我决定
为free()编写一个包装器来做这件事,我想知道为什么free()
本身并没有这样做。
Aaron
-
/ usr / bin / fortune说:
你怎么能在系统工作人如此拥挤?
没有愚蠢的问题。按照设计,free()接收一个值,即要释放的分配的
地址。它不知道
的价值来自哪里。考虑..
int * arr,* tmp;
arr = malloc(N * sizeof * arr);
tmp = arr;
... arr和tmp都保存malloc()返回的内存地址。它现在无论我打电话都没有任何区别。
免费(arr);
或者
free(tmp);
...因为free()函数接收到分配的地址而且
没有关于arr或者tmp。 free()不能将
设置为NULL。
-
Joe Wright
所有内容都应该是虽然简单,但并不简单。
---阿尔伯特爱因斯坦---
这不是一个愚蠢的问题,但*是*常见问题(7.21)
如果free()修改它的论点是这样的,它不可实现
作为C函数。
-thomas
I apologize if this is a stupid question. I was just curious... is
there any reason why free() doesn''t set the pointer (that was passed to
it) to NULL after giving the memory back to the heap? I decided to
write a wrapper for free() to do just that, and I wondered why free()
itself didn''t do it.
Aaron
--
/usr/bin/fortune says:
How can you work when the system''s so crowded?
There are no stupid questions. As designed, free() receives a value, the
address of the allocation to be freed. It doesn''t know where the value
came from. Consider..
int *arr, *tmp;
arr = malloc(N * sizeof *arr);
tmp = arr;
...Both arr and tmp hold the address of memory returned by malloc(). It
doesn''t make any difference now whether I call..
free(arr);
or
free(tmp);
...because the free() function receives the address of the allocation and
no information about arr or tmp at all. It is not possible for free() to
set them to NULL.
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
It''s not a stupid question, but it *is* a FAQ (7.21)
If free() modified its argument like this it wouldn''t be implementable
as a C function.
-thomas
Some of use don''t believe this would be a particularly useful feature.
If the goal is to be able to test a pointer in order to determine
whether it still points to valid accessible memory, a test against NULL
is not sufficient. Consider:
int *p1 = malloc(5 * sizeof *p1);
int *p2 = p1;
magic_free_and_NULL(p1);
if (p1 != NULL) /* OK */
{
p1[0] = 1234;
}
if (p2 != NULL) /* BAM! Undefined. */
{
p2[1] = 4321; /* BAM! Undefined. */
}
In this example, it''s not even safe to test p2, let alone dereference
it. (The value of a pointer to memory that has been freed is indeterminate.)
Also, consider this:
free(p - 1);
What should be set to NULL here?
Setting freed pointers to NULL is handy in some cases, but is not good
as a general technique for determining when memory has been freed.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
这篇关于free()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!