size_t confusion in functions like snprintf

309 Views Asked by At

In functions like snprintf, strlcat, and strlcpy where their manpage mentions size_t size in the arguments of said functions, what exactly is size, or what's the best way to get size?

Taken from strlcpy(3), strcat(3), and printf(3) (with comments added)

size_t
strlcpy(char *dst, const char *src, size_t size);
//                                         ^^^^

char *
strncat(char *str, const char *src, size_t n);
//                                         ^

int
snprintf(char *str, size_t size, const char *format, ...);
//                         ^^^^  

My understanding was that size could (or in the case of strncat, should?) be obtained like so:

sizeof dst - strlen(dst) - 1 
// sizeof dst buffer, minus the offset of '\0', minus 1 for the null-terminator

But I recall reading somewhere on SO that to get the size of a variable that you did something like:

sizeof <VAR> / <SOMETHING ELSE?>
// sorry, I don't remember the rest of this method

Is there a difference between the two forms, are they equivalent and/or interchangeable, or are they only valid in certain circumstances?

EDIT: I think I understand it a little bit better now. sizeof returns the size in bytes of whatever you pass to it, but in same cases you need to take in account the size of the destination buffer in addition to the size of the source buffer, as in the case of strncat.

1

There are 1 best solutions below

0
On BEST ANSWER

For strlcpy, you give it the size of the buffer. If the buffer has size 100, strlcpy can copy up to 99 chars plus a zero byte.

For strlcat, you give it the size of the buffer. strlcat figures out how many bytes are already there.

The whole point of strlcpy, strlcat, snprintf is that you give it the size of the buffer and the function figures out the rest, instead of you calculating how many bytes are available. That's because people calculating sizes make mistakes, so calling strlcpy and calculating how many bytes are available yourself defeats the purpose.