Question:
Question on malloc() & free()?
Guru
2008-01-24 07:26:23 UTC
1. When we try to malloc() and suppose enough memory is not available what kind of error can i expect? Can i see system crashing? Segmentation fault or Bus Error?
2. When i do free(ptr) it frees the memory, but in many implementations I have noticed we give explicitly ptr=NULL; after free(ptr)
free(ptr);
ptr=NULL;
Why do we give ptr=NULL; explicitly?
Three answers:
spoonmeiser
2008-01-24 07:36:57 UTC
It'll be easier to answer the second question first, so here goes:



It's fairly common to check a pointer to see if it's NULL before using it, to make sure that it is a valid pointer.



After you free the memory used by whatever a pointer was pointing at, you'll still have a pointer pointing to the same memory location, even though this memory location might subsequently be reassigned and used for some other purpose.



By setting the pointer to NULL, you make sure that you don't accidentally use the pointer elsewhere in your code: If you check for NULL pointers, you'll discover that this pointer is NULL, if you don't check (tsk tsk) then your program will likely crash, which is probably better then having unpredictable memory corruption since it will be easier to debug.



If you malloc and there is insufficient memory available, the returned pointer will be NULL.



It is important to remember that pointers and allocated memory are seperate. You can have a pointer pointing to unallocated memory, and you can have allocated memory without anything pointed to it. Although you generally want to avoid either of these situations.
Adopted
2008-01-24 15:34:51 UTC
The malloc function returns NULL if insufficient memory is provided/available. So your pointer would be null.







The reason you are setting ptr to NULL is because it still holds an address. free, freed the memory that ptr is pointing to, but ptr is still pointing at that memory. It must be set to null.
charsoxer
2008-01-24 15:43:24 UTC
1. Your system won't crash etc. However it will return you a bad pointer. Therefore if you try to access it afterward you allocate it you will get a segfault.



2. You free up the memory however you are still pointing to that memory block which now contains gibberish so you need to set it back to NULL.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...