On Wed, Mar 29, 2023 at 5:02 AM Fotis Panagiotopoulos <f.j.pa...@gmail.com>
wrote:

> > In my opinion asprintf should set the pointer to NULL, to be safe.
> > But the calling code should probably be changed as well, because it is
> > not a good coding example for portability.
>
> I'm sceptical about this.
> Setting the pointer to NULL seems more safe, but also it is a change in
> functionality!
>
> Consider the following example:
>
> char * msg = "Error message";
> asprintf(&msg, "format string", args...);
>
> Based on the current functionality, I can directly use msg without any
> error checking, as it will always be valid.
> (Either due to its initialization, or due to a successful asprintf).
>
> Indeed, this seems like a not-so-great piece of code, but I don't know
> whether this approach is used anywhere in NuttX
> (or in user code).
>


The above usage may work on some implementations but not others. As Bernd
Walter pointed out from some *BSD manpages, some implementations will set
your msg pointer to NULL, losing your fallback string. So code that runs
perfectly well on one OS may break when run on another.

If you have many usages like that, you could encapsulate the
asprintf-or-default-string functionality in a function you can write for
that purpose. You'd utilize vararg and vasprintf for it.

Cheers
Nathan

Reply via email to