Is `asprintf` thread safe?

Is the GNU asprintf function (print highlighted line) thread safe?

(The IIC basically boils down to whether malloc thread safe.)

Consider a code example:

 #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 global variables. What if my getValue is called in parallel threads? Nothing bad will happen, right?

+6
source share
2 answers

Yes, it is thread safe, except when it reads a locale.

asprintf

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

On the exception , in particular:

Functions annotated with the locale as an MT-Safety issue read from the locale object without any form of synchronization. Functions annotated with a locale, called simultaneously with changes to the locales, can behave in such a way that they do not correspond to any of the locales that were active during their execution, but are an unpredictable combination.

These functions are called "conditionally" multithreaded, because in some contexts they turn out to be different, so the programmer needs to take care of this.

+6
source

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

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

It looks like it causes a malloc safe thread and related things.

+2
source

Source: https://habr.com/ru/post/982597/


All Articles