tags:

views:

329

answers:

6

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.

+3  A: 

The second example is bad code - it shouldn't be referencing current after it has been freed. This will appear to work in many cases but it's undefined behaviour. Using tools like valgrind will flush out bugs like this.

Please cite whatever book(s) you have seen this example in, because it needs to be corrected.

Paul R
http://bytes.com/topic/c/answers/212665-freeing-simple-linked-listC primer plus (all editions, 5th, 4th...)
dontoo
Thanks - I knew that the books that the Indian colleges use for C programming are pretty bad (Kanetkar, Balaguruswami, etc) but I guess that the problem is more widespread.
Paul R
+17  A: 

The second program is invoking undefined behavior. It is not a difference in the compiler, but rather a difference in the implementation of the C standard library and the function free(). The compiler will store the pointer current as a local variable, but it will not store a copy of the memory that it references.

When you invoke free(), you give up ownership of the memory being pointed-to by the pointer passed to the free() function. It is possible that after you relinquish ownership, the contents of the memory pointed-to are still reasonable and are still valid memory locations in your process's address space. Consequently, it is possible that accessing them will appear to work (note that you can silently corrupt memory this way). A pointer that is non-null and points to memory that has already been relinquished is known as a dangling pointer and is incredibly dangerous. Just because it may appear to work does not mean it is correct.

I should also point out that it is possible to implement free() in such a way as to catch these errors, such as using a separate page per allocation, and unmapping the page when free() is called (so that the memory address is no longer a valid address for that process). Such implementations are highly inefficient, but are sometimes used by certain compilers when in debugging mode to catch dangling pointer errors.

Michael Aaron Safyan
It would probably be easier to put the address of the last 4 frees in the DR0-DR3 registers and put a read breakpoint on all of them.
MSalters
+11  A: 

After you do free(current), the memory pointed to by current (where current->next is stored) has been returned to the C library, so you shouldn't access it anymore.

The C library can change the contents of that memory at any time - which will result in current->next being corrupted - but it also might not change some or all of it, particularly so soon. That's why it works in some environments, and not others.

It's kind of like driving through a red traffic light. Sometimes you'll get away with it, but sometimes you'll be run over by a truck.

caf
+4  A: 

The best way to find out how compilers work is not to ask about how they handle invalid code. You need to read a book (more than one, actually) on compiling. A good place to get started would be to check out the resources at http://stackoverflow.com/questions/1669/learning-to-write-a-compiler.

anon
+1  A: 

Actually that's the C runtime, not the compiler. Anyway the latter code contains undefined behavior - don't do it. It worked for someone on some implementation, but as you see it crashes nastily on yours. It could damage something silently just as well.

The possible explanation of why the later might work is that on some implementation free() doesn't modify the block contents and doesn't return the memory block to the operating system immediately, so dereferencing a pointer to the block is still "legal" and the data in the block is still intact.

sharptooth
A: 

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 don't think so.

I just want to understand how compilers work.

Here is an example with GCC Compiler (I do not have VC++)

struct film { film* next; };

int main() {
  film* current = new film();
  delete current;

  return 0;
}

;Creation
movl    $4, (%esp)   ;the sizeof(film) into the stack (4 bytes)
call    _Znwj        ;this line calls the 'new operator' 
                     ;the register %eax now has the pointer
                     ;to the newly created object

movl    $0, (%eax)   ;initializes the only variable in film

;Destruction
movl    %eax, (%esp) ;push the 'current' point to the stack
call    _ZdlPv       ;calls the 'delete operator' on 'current'

If it was a class and has a destructor, then it should be called before we free the space the object occupies in the memory with the delete operator.

After destroying the object and freeing its memory space, you can no more reference current->next safely.

Bakkal