NetBSD-Docs archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

strcpy(3) examples use of sizeof



Hi,

In strcpy(3), the examples currently show:

char chararray[6];
(void)strncpy(chararray, "abc", sizeof(chararray));

(and other similar examples).

I've observed people learning to code make the common
mistake of assuming that 'sizeof' will give you the
size of any buffer, including one that's dynamically
allocated.  That is, they may take the example from
the manual page and change it to something like

char *buf;
buf = malloc(BUFSIZ);
strncpy(buf, data, sizeof(buf));

Now the example code in the manual page does the right
thing because the array is of a fixed size known at
compile time, but in the code above, 'sizeof(buf)'
will return 8 and lead to unexpected behavior.

This isn't obvious to many people, and I wonder if it
would make sense to change the example code in the
manual page to not use 'sizeof', so as not to offer
code that can be copied without context, e.g.,

#define NUM 6
char chararray[NUM];
(void)strncpy(chararray, "abc", NUM);

I can imagine arguments being made that people should
not copy code from manual pages without understanding
it (and I'm at least somewhat sympathetic to that
point of view as well).  So...  your thoughts?

-Jan


Home | Main Index | Thread Index | Old Index