Results 1 to 4 of 4
I am in the development of a multiple threaded app (POSIX threads). As usual, I have mallocs and free calls to get and free memory. When I run the app ...
- 12-02-2008 #1Just Joined!
- Join Date
- Dec 2008
- Posts
- 2
malloc fails in multiple pthreads
I am in the development of a multiple threaded app (POSIX threads). As usual, I have mallocs and free calls to get and free memory. When I run the app with multiple threads, I hit upon malloc failed case (no more mem available) but with single thread, it is fine. I want to know whether there is any extra care that needs to be taken to ensure memory is freed in multiple threaded env ?
- 12-02-2008 #2No, no extra care is needed. You should free memory that you no longer need. This is true whether or not you use threads.I want to know whether there is any extra care that needs to be taken to ensure memory is freed in multiple threaded env
You are getting a NULL pointer as the result of a malloc(), yes? In that case, do all your malloc()s like this:
The reason to do it like this is that one of the trickiest parts of threads is keeping one thread from corrupting memory used by another thread. Perhaps something is corrupted in the heap so that when you calculate block_size, you're getting not the size you really want, but something really, really huge.Code:block_size=(however you calculate the block size); pointer1=malloc(block_size); if(pointer1==NULL) { fprintf(stderr,"failure to malloc(%d)\n",block_size); exit(1); }
Just a possibility.
But the answer to your main question, once again, is that using threads raises no special requirements when using malloc() or free().--
Bill
Old age and treachery will overcome youth and skill.
- 12-03-2008 #3Just Joined!
- Join Date
- Dec 2008
- Posts
- 2
You mentioned interesting point - how can we make sure that memory of one thread does not interfere with another one?
- 12-03-2008 #4Don't write any incorrect code.how can we make sure that memory of one thread does not interfere with another one?
Scary, I know. That's why I only use threads when I need them, and then keep the software as simple as possible.--
Bill
Old age and treachery will overcome youth and skill.


Reply With Quote