http://www.politiker-stopp.de/gfx/politiker-stopp-print.png
Stoppt die Vorratsdatenspeicherung! Jetzt klicken &handeln! Willst du auch an der Aktion teilnehmen? Hier findest du alle relevanten Infos und Materialien:

[] strcpy and \0 RSS feed for section TechSucks

Suppose you have a char foo[11]; that you want to put a 10-Byte Text into. For simplicity you copy and paste a line that you had used just a little earlier:

strncpy(foo, "1234567890", 10);

To me, this first looked harmless and even worked fine. At least, mostly. I pretty soon found out that strncpy doesnr't add a final \0. So in the end it became this after all:
sprintf(foo, "1234567890");


EOF

Back home  clock 06:42:15 31.08.2009 | Permalink | Trackback URI

mirabilos (2009-08-31 10:20:47)

Just use http://www.mirbsd.org/man3/strlcpy ☺ That one will always ensure
the output is a valid C string if its input is.

P2501 (2009-08-31 13:41:23)

Ugh. Beginners mistake. You ordered strncpy to copy ten bytes, and so it did. Check the manpage.

Really, the only safe and portable way to do this is:

strncpy(foo,"1234567890",10);
foo[sizeof(foo)-1] = '\0';

strlcpy does a better job, but it's BSD-specific.

blindcoder (2009-08-31 17:30:18)

Guess it means I've been away from C for far too long if I make these mistakes :-)
Switching from doing Perl and bash for one, two years back to a 'You asked for it, you got it'-language does these things to me.

mirabilos (2009-09-01 14:36:13)

strlcpy is not BSD-specific. Actually, almost everyone EXCEPT glibc and
eglibc package it. On Debian, it’s in libbsd. And it’s very few code to
add to the own package, which is what mksh does. Less than GNUlib.

It's better to use memcpy than strncpy.

P2501 (2009-09-01 15:43:19)

(/me goes checking once more)

Okay. Looks like almost everyone else has adopted strlcpy by now, so yes, it's not really BSD-specific anymore. Even uClibc and dietlibc have it.

It's just the glibc maintainers who claim that strlcpy is non-standard and unsafe (as it doesn't completely avoid boundary errors), and therefore should not be supported. Oh, well...

Leave a comment

Allowed HTML tags: a abbr acronym b blockquote em li ol p strong sub sup u ul

Name


Link (enter mailto:you@address.com for mailaddress, otherwise http:// is implied)


Comment