Question about compilers and how they work
Posted
by Marin Doric
on Stack Overflow
See other posts from Stack Overflow
or by Marin Doric
Published on 2010-04-14T10:25:27Z
Indexed on
2010/04/14
10:33 UTC
Read the original article
Hit count: 281
This is the C code that frees memory of a singly linked list. It is compiled with Visual C++ 2008 and code works as it should be.
/* Program done, so free allocated memory */
current = head;
struct film * temp;
temp = current;
while (current != NULL)
{
temp = current->next;
free(current);
current = temp;
}
But I also encountered ( even in a books ) same code written like this:
/* Program done, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
If I compile that code with my VC++ 2008, program crashes because I am first freeing current and then assigning current->next to current. But obviously if I compile this code with some other complier ( for example, compiler that book author used ) program will work. So question is, why does this code compiled with specific compiler work? Is it because that compiler put instructions in binary file that remember address of current->next although I freed current and my VC++ doesn't. I just want to understand how compilers work.
© Stack Overflow or respective owner