Is the behavior of `sprintf` with a `NULL` format string defined?

3k views Asked by At

A junior colleague wrote something like this:

char str[20] = "Normal"; // declared globally

void somefunc(void)
{
  sprintf(str, NULL);
  if (var == TARGET)
  {
    sprintf(str, "Set");
  }
  else
  {
    sprintf(str, "Normal");
  }
}

Besides recommending using snprintf instead, I was contemplating what sprintf would do with a NULL format string (in the first line of the func) - not a NULL value string, but the format control itself. I didn't see anything in documentation I've read.

Is this covered in a standard, or is it perhaps implementation defined? As he's apparently running this code, it must not be causing a segmentation fault here (dereferencing NULL), but is that standard? Is there something I can point to that says "Don't do this.", or is it perhaps perfectly safe (by standard/definition)?

At best it seems an unnecessary statement, but at worst I'm concerned another compiler could cause a segfault here...

1

There are 1 answers

3
Vlad from Moscow On BEST ANSWER

Such a call invokes undefined behavior because (7.21.6.1 The fprintf function; and this is valid for sprintf)

3 The format shall be a multibyte character sequence...