gabriel rosenkoetter on Mon, 17 Jun 2002 05:30:18 +0200


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

Re: [PLUG] unix cp function call (thanks)


On Sun, Jun 16, 2002 at 06:43:50PM -0400, Walt Mankowski wrote:
> I'm not arguing the pros and cons of using system, which have already
> been discussed here.  But I just don't think the fact that both
> filenames are char *'s is a reason not to use it.  You really need to
> become comfortable working with char *'s if want to program
> effectively in C.

How is knowing how to pass them to fopen(3) being less capable of
using char *s in C?

> Here's some sample code that does the cp using system where the two
> filenames are char *'s.  Even if you decide not to use system to do
> the copy, perhaps you'll be able to use it as an example elsewhere in
> your program.

Whoopty-doo. I already posted a lot of code that uses char *s to do
a variety of things. Fred seemed comfortable with it.

>   /* add 5 extra bytes for "cp", two spaces, and a trailing null */
>   cmd = malloc(strlen(to) + strlen(from) + 5);
>
>   sprintf(cmd, "cp %s %s", to, from);

Guh. Evil. Use realloc(3)[1] and snprintf(3). Never use a s*(); use the
sn()* version, and please, please, please check the values of your
strlen(3) for sanity[2]. For that matter, you really shouldn't be
trusting snprintf(3); it's been broken on a variety of vendor's
libcs here and there (off by one errors, improper \0-termination);
you should really be using memcpy(3).

[1] I say use realloc(3) just because it's intensely easier to
deal with if you're doing anything fancier than this, not because
it's actually necessary in this example. It's something where you
should really double-check your vendor's implementation, though,
since it can be totally insane easily if improperly ported (say, to
a 64-bit architecture). That's more of an issue if you're worried
about memory footprint than security, though.

[2] Yes, Walt, I know you said you weren't doing error checking, but
it's important to know what error checking it's really important to
always do in code you're actually going to use.

-- 
gabriel rosenkoetter
gr@eclipsed.net

Attachment: pgpZriCZLr5Ir.pgp
Description: PGP signature