6

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?

1

2 Answers 2

6

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.

2
  • I've just looked at the referenced POSIX Safety Concepts, and there is no hint about the locale exception. So, for me to able to read these lines like the "Preliminary: ..." above, I need additionally to understand the meaning of the modifiers like "locale", "heap", "mem". Where can I look up those? Feb 17, 2015 at 13:38
  • 2
    Some platforms offer asprintf_l which takes a locale_t parameter and should be completely thread-safe.
    – nwellnhof
    Feb 17, 2015 at 14:28
2

glibc is free software and is probably the only (or the most important) library implementing asprintf.

So you can study (and even contribute to improve) its source code. See its stdio-common/asprintf.c & libio/vasprintf.c source files.

It looks like indeed, it is calling in a thread safe manner malloc and related things.

4
  • 2
    is that K&R function parameter style?
    – bolov
    Feb 17, 2015 at 13:32
  • Yes for _IO_vasprintf Feb 17, 2015 at 13:57
  • 1
    Any particular reason why that is used in glib ... in 2015?
    – bolov
    Feb 17, 2015 at 14:25
  • 1
    Because nobody cared to send a patch for the transition to C99. If you care, please fill the legal papers and propose the patch. See glibc contribution checklist Feb 17, 2015 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.