no, this means, that a is a valid pointer that points to a memory location somewhere on your ram that your app has access to. freeing only means that now that location can be used by a newly allocated variable.
no, this means, that a is a valid pointer that points...
Actually, many textbooks call these pointers "invalid pointer". ;-)
Accessing freed memory is "undefined behaviour" which basically means, the compiler is free to do what he likes (which is usually just access the old memory, but don't count on this. Some optimizations may reuse the memory quicker than you expect..)
When you free memory, all it means is that the memory is free to be reallocated to somewhere else from that point on. It does not guarantee that dereferencing it gives you garbage data/segmentation fault etc...
That memory address will contain 42 until the program uses that memory again for another dynamically allocated variable.
There have been some somewhat ambiguous responses to this question. I feel I should spell this out clearly:
1 2 3
free(a);
*a = 42;
This is HEAP CORRUPTION. You're writing to an invalid address (the address is no longer valid because the memory is freed).
If you're very lucky, this will crash to show you that something is horribly wrong. However more than likely you'll just corrupt the heap which is the worst kind of bug. It can make your program behave very strangely. These kinds of bugs are extremely difficult to find.
Never ever ever do this.
is there any real way to verify that the free function actually worked?
Another quick question, is there any real way to verify that the free function actually worked?
You should assume that functions do what they're supposed to do. It's impossible to write
software that has to defend against functions that don't work. At that point why would you
even assume that your compiler generates the correct machine code?
Oh wow...I didn't even read his first post where he shows that he's dereferencing a free'd pointer.
I thought the pointer had 42 in it before he free'd it (lack of reading the actual code), and dereferenced it and wondered why it still had 42 in it.
So you say that I should never check if malloc failed because I should assume that it does what it's supposed to do?
No. It does what it's supposed to do, which is attempt to allocate n bytes of memory on the heap. It is not malloc's fault if it can't allocate that memory for you. malloc fails when the operating system can't or won't give you more memory. It doesn't just fail for no reason.