There are many questions on this website regarding freeing pointers after use and, further, setting them to NULL. Arguments are fierce and the topic is seemingly divided equ
"Why would writing to a memory block that was previously freed, that still has the original pointer to it, cause the program to crash? -- See the first paragraph of the first post to the question linked above (if I missinterpreted the intent of this paragraph, please explain because it is not explicit on whether that pointer is used again to write the memory or a new pointer is created.)"
I think reusing the same memory space after it has been free'ed is equal to 'crime', atleast for Kmem(slab allocation) based designs(I think mostly used in linux..correct me if I am wrong).
To understand the reason we need to see how things work inside(you can skip and just read the conclusion at the end):
In simple embedded systems, many pages in memory are divided into objects usually of size 2^y(e.g. 8 bytes, 16 bytes etc). So when you request z bytes of memory by malloc, where
16 < z <=32
The system returns one object from the pool of 32 byte objects held in some page having free objects. After assigning you this object, OS makes changes to the 'slab' data structure and marks the object at a given address as non-free.
When you call free(), the object is returned to the slab pool as a free object and the OS can reassign it if other malloc call happens. This call can be made by your code or some other component running in the os.
**So if you reuse the free'ed memory which the os had previously assigned to your code. Then you might be writing to some memory location which might be used:
Further, some other component who the OS re-assigned the pointer too could also over-write on your data.
And this can cause severe data corruption.
Further, make sure that you dont write more data to the memory, than what you requested through malloc(). Doing this can cause :