first of all let me say that I started to study the C three days ago. As exercise I'm reading source code as much as I can. I thought I'd start with Tor and, in this file src/common/compat_libevent.c
, I found something that has puzzled me (n = strlcpy(buf, msg, sizeof(buf));
):
STATIC void
libevent_logging_callback(int severity, const char *msg)
{
char buf[1024]; //size of buf
size_t n; //store the maximum size of n
if (suppress_msg && strstr(msg, suppress_msg)) //if suppress_msg is not NULL and in suppress_msg there is msg...
return;
n = strlcpy(buf, msg, sizeof(buf)); //here I'm confused: msg, for example, of 2048 bytes will lead to a buffer overflow... or not?
if (n && n < sizeof(buf) && buf[n-1] == '\n') {
buf[n-1] = '\0';
}
...
A msg
, for example, of 2048 bytes will lead to a buffer overflow, right (or not)?
BUFFER_LENGTH
as a global variable. That's poor form. Secondly,sizeof
is a placeholder that is expanded to a constant size at compile time and will always be the size ofbuf
. There aren't any concerns, this is already better coding practice than your suggestion.