Search code examples
cmultithreadingprintfglibcasprintf

Is `asprintf` thread-safe?


Is the GNU function asprintf (print to allocated string) thread-safe?

(IIC, basically, this boils down to the question whether malloc is thread-safe.)

Consider the example code:

#define _GNU_SOURCE
#include <stdio.h>

#include "getValue.h"

char * getValue(int key) {
  char * value;
  asprintf(&value, "%d", key); // TODO: No error handling!
  // If memory allocation wasn't possible, or some other error occurs,  these  functions  will
  // return -1, and the contents of strp is undefined.
  return value;
}

Here, I do not touch any global variables. What if my getValue gets called in concurrent threads? No bad things will occur, will they?


Solution

  • Yes, it's thread safe except when it reads the locale.

    asprintf

    Function: int asprintf (char **ptr, const char *template, …)
    Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem

    About the 'locale' exception, in particular:

    Functions annotated with locale as an MT-Safety issue read from the locale object without any form of synchronization. Functions annotated with locale called concurrently with locale changes may behave in ways that do not correspond to any of the locales active during their execution, but an unpredictable mix thereof.

    These kinds of functions are known as "conditionally" multithread safe because, in some contexts, they turn out not to be, so the programmer needs to take care of that.