Printf: Is it safe?

I'm just wondering if this expression is safe:

int main (void)
{
  char my_tab[256];

  memset(my_tab,0x61,sizeof(my_tab));

  printf("Is it safe ? : %.256s",my_tab); /* is it safe ? */
}
+4
source share
3 answers

Yes, you print 256 characters and no more.

From standard C11 7.21.6. p4:

, d, i, o, u, x X, a, A, e, E, f F , g G , , s . (.) * ( ), ; , . , undefined.

7.21.6.1. P8:

s: l, . ( ) . , , . , .

+6

.

printf (3) - Linux http://man7.org/linux/man-pages/man3/printf.3.html:

   s      If no l modifier is present: The const char * argument is
          expected to be a pointer to an array of character type
          (pointer to a string).  Characters from the array are written
          up to (but not including) a terminating null byte ('\0'); if a
          precision is specified, no more than the number specified are
          written.  If a precision is given, no null byte need be
          present; if the precision is not specified, or is greater than
          the size of the array, the array must contain a terminating
          null byte.

vsnprintf /lib/vsprintf.c strnlen (s, spec.precision), :

/**
 * strnlen - Find the length of a length-limited string
 * @s: The string to be sized
 * @count: The maximum number of bytes to search
 */
size_t strnlen(const char *s, size_t count)
{
    const char *sc;

    for (sc = s; count-- && *sc != '\0'; ++sc)
        /* nothing */;
    return sc - s;
}

char.

static noinline_for_stack
char *string(char *buf, char *end, const char *s, struct printf_spec spec)
{
    int len, i;

    if ((unsigned long)s < PAGE_SIZE)
        s = "(null)";

    len = strnlen(s, spec.precision);

    if (!(spec.flags & LEFT)) {
        while (len < spec.field_width--) {
            if (buf < end)
                *buf = ' ';
            ++buf;
        }
    }
    for (i = 0; i < len; ++i) {
        if (buf < end)
            *buf = *s;
        ++buf; ++s;
    }
    while (len < spec.field_width--) {
        if (buf < end)
            *buf = ' ';
        ++buf;
    }

    return buf;
}
+2

, . , , .

%.Ns, N - , :

size_t count = 0;
size_t N = ...;
char *ptr = <next-arg>;
while (count < N && *ptr != '\0') {
    putchar(*ptr++);
    count++;
}

, , N.

, while, . , , , :

[7.19.6.1.8] , .

+1

All Articles