[Solved] Using sizeof with sprintf/vsnprintf corrupts text


Put in your code somewhere:

printf ("size is %d\n", sizeof (putbuf));

If it’s a pointer, you’ll probably get four or eight since that’ll be the size of a pointer on your system (four or eight will be common ones at the moment but it all depends on the size of your pointers).

Remember that arrays will decay into pointers in the vast majority of cases.

For example:

#include <stdio.h>

void fn (char x[]) {
    printf ("size in fn = %zd\n", sizeof (x));
}

int main (void) {
    char x[100];
    printf ("size in main = %zd\n", sizeof (x));
    fn (x);
    return 0;
}

output this on my system:

size in main = 100
size in fn = 4

If you want to pass the actual size information, you need to do it explicitly:

#include <stdio.h>

void fn1 (char x[]) {
    printf ("size in fn1 = %zd\n", sizeof (x));
}

void fn2 (char x[], size_t szx) {
    printf ("size in fn2 = %zd\n", szx);
}

int main (void) {
    char x[100];
    printf ("size in main = %zd\n", sizeof (x));
    fn1 (x);
    fn2 (x, sizeof (x));
    return 0;
}

or, alternatively, for allocated memory:

#define SZ 512
int main (void) {
    char *x = malloc (SZ);   // warning, may fail, irrelevant here.
    printf ("size in main = %zd\n", sizeof (x));
    fn2 (x, SZ);
    free (x);
    return 0;
}

7

solved Using sizeof with sprintf/vsnprintf corrupts text