skip to Main Content

Consider the following code:

char buffer[5]{};
snprintf(buffer, sizeof(buffer), "hi");

snprintf writes 'h', 'i' and '' to buffer.

My question is: is there any guarantee that the snprintf won’t touch buffer[3] and buffer[4] according to the standard? Visual Studio 2019 keeps the unused buffer untouched, but is this a standard behavior?

2

Answers


  1. The N1548 draft ISO/IEC 9899:201x Programming languages — C

    7.21.6.5 The snprintf function

    Synopsis

    1. #include <stdio.h>
      int snprintf(char * restrict s, size_t n,
           const char * restrict format, ...);
      

    Description

    1. The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

    Returns

    1. The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

    It clearly defines how much characters would be written. It does not guarantee that characters are not modified in the target buffer after the returned value + 1.

    If you run your code in POSIX environment and if such the guarantee is a requirement, you can use a memory stream opened with fmemopen() and used with fprintf(). fprintf() guarantees that it will not modify characters after the terminating null character.

    char buffer[5]{};
    FILE* f = fmemopen(buffer, sizeof(buffer), "w");
    fprintf(f, "hi");
    fclose(f);
    
    Login or Signup to reply.
  2. I cannot think of a reason that it will alter content in the remaining space. But if you are worried about that, determine the length before calling snprintf() in the code like below.

    int main() {
        char buffer[5]{};
        char p[] = "hi";
        size_t len = strlen(p);
        size_t num = len < sizeof(buffer) ? len + 1 : sizeof(buffer);
        snprintf(buffer, num, p);
        return 0;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search