今天看一段程序,C真是少用。如下,是双向链表的清空操作:
void bilistClear(Node *bl){
if(bl->data!=NULL){
free((char*)bl->data);
bl->data=NULL;
}
if(bl->pre!=NULL)
bl->pre->next=NULL;
bl->pre=NULL;
if(bl->next==NULL)
return;
bilistClear(bl->next);
free(bl->next);
bl->next=NULL;
}
发现,free后还要置为NULL。
以下是MSDN关于free的解释:
The free function deallocates a memory block (memblock) that was previously allocated by a call to calloc, malloc, or realloc. The number of freed bytes is equivalent to the number of bytes requested when the block was allocated (or reallocated, in the case ofrealloc). If memblock is NULL, the pointer is ignored and free immediately returns. Attempting to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors.
If an error occurs in freeing the memory, errno is set with information from the operating system on the nature of the failure. For more information, see errno, _doserrno, _sys_errlist, and _sys_nerr.
After a memory block has been freed, _heapmin minimizes the amount of free memory on the heap by coalescing the unused regions and releasing them back to the operating system. Freed memory that is not released to the operating system is restored to the free pool and is available for allocation again.
When the application is linked with a debug version of the C run-time libraries, free resolves to _free_dbg. For more information about how the heap is managed during the debugging process, see The CRT Debug Heap.
free is marked __declspec(noalias), meaning that the function is guaranteed not to modify global variables. For more information, seenoalias.
To free memory allocated with _malloca, use _freea.
看来free只是表示此处内存可供allocate(Freed memory that is not released to the operating system is restored to the free pool and is available for allocation again.)而之前的值并没有被清空。因此为了某些安全考虑free后置其值为NULL。如果它的值还有用,那再另说了。