Quote:
Originally Posted by
JamesGoh
Is it generally not a good idea in a multithreaded program to make lots of malloc calls (dynamic memory requests) because of the limited nature of the memory heap ?
Out of curiosity (warning it may sound silly), but would using mutexs (mutual exclusion) help to minimise chances of runtime errors ?
regards
Its not about a good or a bad idea in using malloc() its about the requirements of the project. You cannot have a project using only static variables. In large projects, without malloc()/calloc(), its not possible to create dynamic variables and objects.
Yeah, the following problems are more prominent in multithread environments than in the single threaded environments ---:
1) Getting dangling pointers
2) Freeing a pointer multiple times (freeing in only one function; but getting the same function called in context of many threads)
3) Getting memory leaks easily.
It's always a trade off; speed vs size + flexibility --:
Accessing static variables are faster (created on the program stacks) than accessing dynamic variables (as these are created on the heaps) and you loose flexibilities (required for large server apps) and the binary size thus produced is bigger compared to using the dynamic variables (unsuitable for embedded applications).
However there are some good tools available like ValGrind, Dmalloc etc. that help in debugging memory related issues and they are very helpful if used along with GDB.
As of the second part of your question on mutexes; it's a bit vague as mutexes are used to control simultaneous access to shared resources where there is a race conditions.
If its not a condition of simultaneous access; one should ALWAYS check as follows --:
If (NULL != myPointer){
..... .....
//use the pointer
.... ....
}; //Before using any pointer to operate through it.
OR in mutual exclusion conditions----:
mutex_lock(&myMutex);
//Below pointer operates on shared memory area.
if (NULL != myPointer){
..... .....
//use the pointer
.... ....
}; //Before using any pointer to operate through it.
mutex_unlock(&myMutex);