Namespaces
Variants
Actions

Talk:c/experimental/dynamic/asprintf

From cppreference.com

In C, copying a string to itself is undefined behavior with most standard library functions, including for sprintf(). Regarding asprintf(), it should be easy enough to avoid any overlapping problems by first creating the new string on the heap, then printing to it, and finally assigning to the char** pointer. It seems to work with GLibC, but I'm not sure whether it's an implementation detail that should not be relied on. I cannot find the function's POSIX specifications, so I'm wondering if anyone has more information on this ? To be clear, I'm wondering if such usage is well-defined:

char *s = "abc";
asprintf(&s, "%s%s%s", s, s, s);
printf("%s", s); // should print abcabcabc

It would be useful to mention this in the article if we find a source for this.

Babbage (talk) 15:43, 5 August 2022 (PDT)

It's not in POSIX, it's a linux function which the C committee picked up into the Dynamic Memory TS. The TS says only that "The asprintf function behaves as sprintf" (and the linux man page similar), so whatever applies to sprintf should apply here. --Cubbi (talk) 20:53, 6 August 2022 (PDT)