Re: strcpy versus strncpy

Edwin Li-Kai Liu (robin.hood@IBM.NET)
Tue, 03 Mar 1998 17:36:13 +0700

Daniel Reed wrote:

> Recently on the vcpp@narnia.mhv.net mailing list someone asked about
> creating their own function similar to printf(), to which I gave the
> minimal example:
>
> [snip]
>
>
> I made a note that this wasn't multi-thread safe, as calling MySprintf()
> again would overwrite the static buffer for MySprintf().

It's not just the problem of non-multithread-awareness. Sometimes it's even
unsafe in a single thread. Really poor coding. Say, if somebody uses the
function structure like this:

void func2(...)
{
char* pStr = MySprintf(...);

// do something ...
return;
}

void func1(...)
{
char* pBuf = null;
pBuf = MySprintf(...);

func2(...);

// do something else with content in pBuf,
// which is already messed up by func2.
// this kind of bug will not be found easily.

}

We'll have to wait for the bug to happen. Soon or late. This issue is very
well-known by most experienced programmers, why that person made this silly
mistake?

> If I had made this use dynamic memory, instead of a static internal
> buffer, the user would then have to deal with free()'ing a section of
> memory they did not allocate--my function did! If nothing else, that's
> poor coding style (in my opinion), and at worse, leads to hard-to-trace
> memory leaks.

If you use C++, you can write a string class (I think someone already did that?
M$?) that uses dynamic buffer allocation and upon object destruction the buffer
is released. This will prevent memory hole, but performance suffers!

> as root, having a static buffer and using strcpy/sprintf/vsprintf, buffer
> overflows are possibly exploitable. As any user, having a dynamic buffer
> and using anything, memory starvation (or CPU starvation, in fact;
> malloc() is an expensive call) is possible. Under any user, using a static
> buffer with strncpy/snprintf/vsnprintf, buffer overflows are significantly
> reduced (if not eliminated), resource starvation is significantly reduced
> (if not eliminated), and at worse an incoming, legitimate message will be
> bounced because it overflows a buffer. I believe in [one of] the SMTP
> RFC[s] a maximum line length is defined for commands.

I think, in general, buffer to store passwords for verification, user info,
general strings, etc. may be truncated as needed. However file names should not
be truncated and the buffer used to store file names should either be dynamic
allocated or bound verified. For some critical occasions, if a string that
exceeds buffer bound is detected, the function should throw an exception or to
return error.

--

Robin Hood Liu Li-Kai, Edwin

ICQ UIN: 1311717 (dauphin)

Sigfile's shortn'd due to req.