0

I am working on porting an old codebase from Borland C to C99. I have come across the following function, which looks like it should copy zero bytes into a buffer.

sprintf(tx_tcp_buf,"%0s%0s%0s%0s%0s%0s",strHeader, ccSTX, drValidity, ccUS, "Y",ccETX);

The declaration of tx_tcp_buf is static BYTE tx_tcp_buf[150] = {0};.

All of strHeader, ccSTX, drValidity, ccUS, and ccETX are of type char *.

What's bugging me is the length specifier in the format string. It is my first time of encountering a length specifier of zero, for a string. Here, we've got %0s which from what I read should copy zero bytes. (So what is the above call to sprintf even doing?)

I don't have a copy of Borland C, but I've tried the following program in GCC:

#include <stdio.h>
int main() {
     char buf[256];
     char * hello = "Hello, World!\n";
     printf(buf, "%0s", hello);
     printf("\"%s\"\n",buf);
}

It's output is

"Hello, World!
"

Evidently the %0s isn't doing much that %s wouldn't do. But with -pedantic -Wall -std=c99, I get a warning, which specifically mentions some gnu_printf format:

warning: '0' flag used with '%s' gnu_printf format [-Wformat=]
       sprintf(tx_tcp_buf,"%0s%0s%0s%0s%0s%0s",strHeader,ccSTX,drStatus,ccUS,"I",ccETX);

Do different compilers have different behaviours here? I'm especially interested in Borland C, and GCC. But it would be good to know about others.

Lorraine
  • 1,189
  • 14
  • 30
  • http://www.bitsavers.org/pdf/borland/borland_C++/Borland_C++_Version_3.1_Library_Reference_1992.pdf page ~400. I only see `0n` as the relevant `Width specifier` but nothing much more - looks like the same as in C. But the `0` is not even in `Flag characters` on page 401. And I have trouble distinguishing `0` from `O`. – KamilCuk Aug 10 '21 at 15:43
  • 2
    "*which from what I read should copy zero bytes*" - where did you read that from? The `0` in `%0s` is not a length specifier at all, it is a flag to specify that the output should be left-padded with leading 0s instead of spaces, if a length were specified. Except in this case, that flag has no effect for `%s`, so it gets ignored. See GCC's [Formatted Output](https://www.gnu.org/software/libc/manual/html_node/Formatted-Output.html) documentation, and CppReference's [printf() documentation](https://en.cppreference.com/w/c/io/fprintf) – Remy Lebeau Aug 10 '21 at 15:49

0 Answers0