[Date Prev][Date Next]
Re: OpenLDAP-specific API
Howard Chu writes:
> In 1986 I proposed that the new ANSI C string library should change
> the definition of strcpy/strcat's return value, (...) This was viewed
> as too radical a change, and the idea was rejected. I then proposed
> that a new function be introduced, with the above-described behavior,
> and that too was rejected.
A more serious problem is buffer overflow, and strncpy/strncat do not
solve them well. Here is a paper which designs two functions that solve
size_t strlcpy(char *dst, const char *src, size_t size);
size_t strlcat(char *dst, const char *src, size_t size);
The functions NUL-terminate the destination string for all
strings where the given size is non-zero. They take the full
size of the destination buffer as a size parameter (i.e.
usually sizeof(buffer)). They do not zero-fill their
destination strings (other than the compulsatory NUL to
terminate the string).
They return the total length of the string they would create if
there was no truncation. To check for truncation, the
programmer need only verify that the return value is less than
the size parameter.
The implementations I have seen make one exception: strlcat does not
truncate the dst string if strlen(dst) <= size.