is sprintf
thread safe ?
//Global log buffer
char logBuffer[20];
logStatus (char * status, int length)
{
snprintf(logBuffer, 19, status);
printf ("%s\n", logBuffer);
}
The thread safety of this function totally depends upon the thread safety of snprintf
/sprintf
.
Updates :
thanks for ur answers .
i dont mind, if the actual contents gts messed up. but want to confirm that the sprintf would not cause a memory corruption / buffer overflow going beyond 20 bytes in this case, when multiple threads are trying to write to logBuffer
?
Regarding your update about not worrying if the
logBuffer
content get garbled:I'm not sure why you want to avoid making your function completely thread safe by using a locally allocated buffer or some synchronization mechanism, but if you want to know what POSIX has to say about it, here you go (http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11):
So, POSIX says that your program needs to make sure mutilple threads won't be modifying
logBuffer
concurrently (or modifyinglogBuffer
in one thread while reading it in another). If you don't hold to that, there's no promise made that the worst that will happen is garbled data inlogBuffer
. There's simply no promise made at all about what the results will be. I don't know if Linux might document a more specific behavior, but I doubt it does.