Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
This is not a C issue, but really about dynamically allocated memory in general. Think about it. When you allocate a chunk of dynamic memory, the heap manager finds an available memory region of ...
#1: Initial revision
This is not a C issue, but really about dynamically allocated memory in general. <i>Think</i> about it. When you allocate a chunk of dynamic memory, the heap manager finds an available memory region of the right size (or tells you it can't give you the requested memory), marks it as in-use, and returns you a pointer to it. When you release the chunk, the heap manager marks it as unused. What happens to the memory after that is not your business. You have no guarantee that the memory hasn't been allocated by another thread, implicitly by the run-time library, or whether the address is even still valid in your address space. It could cause a memory fault if you try to read from it. <blockquote>Is reading the address returned by a heap allocation function after its deallocation truly an instance of undefined behavior?</blockquote> Yes! That's the point of deallocating memory. You are saying that you're done with it. That means something else is free to use it, and may have by the time you try dereferencing the pointer again. Depending on the OS, it may have been marked as invalid memory for you and trigger some kind of trap when you try to access it. Again, <i>think</i> about it. How else do you expect it to work? If you still wanted to access the memory, then you wouldn't deallocate it yet. Once you do deallocate it, it's not yours anymore.
