两次免费调用指针

问题描述:

在课堂上我被教过,在指针上两次调用free()确实非常糟糕.我知道这是一种好习惯,在释放它之后立即将指针设置为NULL.

I have been taught in lectures, that calling free() on a pointer twice is really, really bad. I know that it is good practice, to set a pointer to NULL, right after having freed it.

但是,我至今仍未听到任何关于其原因的解释.据我了解,malloc()的工作方式,从技术上讲应该跟踪已分配并给您使用的指针.那么,为什么不知道通过free()接收到的指针是否已经释放呢?

However, I still have never heard any explanation as to why that is. From what I understand, the way malloc() works, it should technically keep track of the pointers it has allocated and given you to use. So why does it not know, whether a pointer it receives through free() has been freed yet or not?

我想了解一下,当您在以前已释放的位置上呼叫free()时,内部会发生什么.

I would love to understand, what happens internally, when you call free() on a location that has previously already been freed.

使用malloc时,是在告诉PC您要为您保留堆中的某些内存位置.计算机会返回一个指向所寻址空间的第一个字节的指针.

When you use malloc you are telling the PC that you want to reserve some memory location on the heap just for you. The computer gives back a pointer to the first byte of the addressed space.

使用free时,实际上是在告诉计算机您不再需要该空间,因此将其标记为可用于其他数据.

When you use free you are actually telling the computer that you don't need that space anymore, so it marks that space as available for other data.

指针仍然指向该内存地址.此时,另一个malloc调用可以返回堆中的相同空间.当您再次调用free时,您不是在释放先前的数据,而是释放新的数据,这可能对您的程序不利;)

The pointer still points to that memory address. At this point that same space in the heap can be returned by another malloc call. When you invoke free a second time, you are not freeing the previous data, but the new data, and this may not be good for your program ;)