NetBSD-Docs archive

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

Re: strcpy(3) examples use of sizeof



On Sat, Dec 10, 2022 at 05:24:24PM -0500, Jan Schaumann wrote:
 > Martin Husemann <martin%duskware.de@localhost> wrote:
 > How do you feel about adding a separate manual page
 > for the sizeof operator?  (See attached proposal,
 > though my mandoc is not very good and likely needs
 > clean up.)

some kibitzing on the page itself, since I'm not by any means
convinced this would be a bad page to have in the system:

(first, since it's an identifier in the C function namespace, even
though it's not actually a function, the page belongs in section 3)

 > .Sh NAME
 > .Nm sizeof
 > operator

Pretty sure having "operator" there is not correct mdoc.

 > .Nd yield the storage size of the given operand

"find", not "yield"

 > The unary
 > .Nm
 > operator yields the storage size of an expression or

Just say that .Nm finds the size. It being an operator rather than a
function is a secondary point and belongs as an aside a later section.

 > data type in
 > .Em char sized units .
 > As a result, 'sizeof(char)' is always guaranteed to be 1.

It is _defined_ to be 1.

 > (The number of bits per
 > .Dv char
 > is given by the
 > .Vt CHAR_BITS

that's CHAR_BIT

 > .Sh EXAMPLES
 > The following example illustrate the possible results
                                  ^s
 > For initialized data or uninitialized arrays of a
 > fixed size known at compile time,
 > .Nm
 > will return the correct storage size:

"correct" does not seem like the right word here.

 > When applied to a struct or union,
 > .Nm
 > returns the total number of units in the object,

"char-sized units", otherwise it sounds like it returns the number of
members in the struct.

 > When applied to a struct containing a flexible array
 > member,
         ^ at the end

since most people, even those with plenty of experience reading the
standard, have no idea precisely what widgetry "flexible array member"
means without looking it up.

 > if ((buf = malloc(BUFSIZ)) == NULL) {
 >         perror("malloc");
 > }
 > /* Warning: wrong! */
 > (void)strncat(buf, input, sizeof(buf) - 1);

Don't encourage people to use strncat. Or even strncpy. Make it
snprintf if you don't want to use strlcpy. And calling strncat on an
uninitialized array is itself wrong :-)

 > Since it is evaluated by the compiler and not the
 > preprocessor, the
 > .Nm
 > operator cannot be used in a preprocessor expression.

There have been compilers where sizeof() works in #if, e.g.
Borland's. FWIW. But it's not standard, nor generally implemented.

(Though TBH, I'm surprised not, given the large number of #defines
about type sizes that a modern compiler's cpp has to know anyway.)

-- 
David A. Holland
dholland%netbsd.org@localhost


Home | Main Index | Thread Index | Old Index