Search code examples
c++cprintfpacket

printf a buffer with nulls


Is there some fancy printf syntax to ignore nulls when printing a string?

Example use case: printing a network packet that contains a bunch of null terminated strings.

My test code to illustrate the issue:

#include <cstdio>
#include <cstring>

void main()
{
    char buffer[32];
    const char h[] = "hello";
    const char w[] = "world";
    const int size = sizeof(w) + sizeof(h);

    memcpy(buffer, h, sizeof(h));
    memcpy(buffer + sizeof(h), w, sizeof(w));

    //try printing stuff with printf
    printf("prints only 'hello' [%s]\n",buffer);
    printf("this prints '<bunch of spaces> hello' [%*s]\n",size,buffer);
    printf("and this prints 'hello' [%.*s]\n",size,buffer);

    //hack fixup code
    for(int i = 0; i < size; ++i)
    {
        if(buffer[i] == 0)
            buffer[i] = ' ';
    }
    printf("this prints 'hello world ' [%.*s]\n",size,buffer);
}

Solution

  • printf assumes strings are c-style (i.e. ending in null characters). You need to do one of the following:

    1) use the write method of ostream (C++ style)

    2) use the write command (from unistd.h, C style)

    3) iterate through each character and print.

    When I am debugging packets, oftentimes I will print out each character using the %02hhx format to be sure I see the exact code (without any quirks about printing null characters to the screen)