Talk:C Programming/Common practices


 * One simple solution to this is to ensure that any pointer is set to a null pointer immediately after being freed

I thought you should not do that this way, because another thread could access that memory after being freed by us and before we assign it the NULL value, which would lead to an unexpected behavior.

I would rather use p = NULL; free (p);

instead of free (p); p = NULL;

trosos 213.220.245.54 12:14, 8 September 2007 (UTC)


 * That won't work. By assigning NULL to p before freeing, p no longer points to the memory location to be freed. This means you've created a memory leak, free may crash your program or cause your program to do strange things (this is known as "undefined behavior"). Also its just as likely that another thread will access p while its set to NULL before free is called, perhaps making p point to something else and causing whatever p points to now to be freed instead, which may not be whats wanted. Better solution is to lock access to the variable so its unaccessible by other threads until after the free is complete. Something like:

thread_lock(p); free(p); p = NULL; thread_unlock(p); --dark lama  12:51, 8 September 2007 (UTC)

I agree with Darklama that calling free with the argument 0 can't possibly work. The free library routine needs to know *which* of many blocks of memory I've malloced that I want to free. If I always call free with the same argument (zero), no matter which block of memory I really wanted to free, then there's no way for the implementation of free to guess which of those blocks I really wanted to free.

Dealing with multi-threaded programming is already tricky, even without trying to give 2 different threads access to the same piece of malloced memory.

A freed block of memory may be immediately re-used and overwritten by some other process. Freeing that memory can be considered a very special variation of writing to that memory. So I think the same techniques used to deal with one or more threads writing to a block of memory and one or more threads reading that same block of memory also apply when one of those threads wants to free that memory.

The general problem is the readers-writers problem. Locking that block so only one thread at a time can access it is *one* good solution. But I think that solution (and others) should be discussed under the topic of multithreading, not under the topic of malloc and free.

Is multithreading entirely outside the scope of this book? If so, what other book is appropriate for discussing multitasking in C -- perhaps Parallel Computing and Computer Clusters?

If multitasking is in the scope of this book, do we need yet another chapter in this book, analogous to C++ Programming/Threading? --DavidCary (talk) 04:01, 19 October 2008 (UTC)