Backup tool?

Colin Watson cjwatson at canonical.com
Tue Oct 19 15:53:05 UTC 2004


On Tue, Oct 19, 2004 at 10:40:22PM +0800, John wrote:
> Colin Watson wrote:
> >On Tue, Oct 19, 2004 at 09:13:08PM +0800, John wrote:
> >>I'm not going to spend much time on this. here are som common C 
> >>functions I believe inherently unsafe because they rely on strings not 
> >>being too long, and which are used in mondo:
> >>strcat()
> >>strstr()
> >>sprintf()
> >>strcpy()
> >>strchr()
> >
> >Not to argue with the rest of your mail, but in what way are strstr()
> >and strchr() inherently unsafe? They aren't. If what you thought was a
> >string was already not null-terminated, you've already lost before
> >calling strstr() or strchr().
> 
> Maybe you're right, as I stressed I'm not expert in C programming. I'm 
> not sure that reading off the end of a string is inherently hazardous, 
> but a premature termination without a user-comprehensible message isn't 
> helpful.
> 
> Is carelessly relying on the returned pointer safe?

Yes. You should check for NULL, but apart from that C's guarantees are
sufficient.

> If I search what I think is a pointer to a string "john.is.wacko" but
> that actually points to some code (do code and data share the same
> address space?) and write to the target, what then?

Then you made a very bad mistake somewhere else, and *any* access
through that pointer is unsafe, not just strstr() and strchr(), and not
just code that iterates over the memory pointed to by that pointer.

In your specific example, most architectures will give you a
segmentation fault.

> What if the area the pointer points to has been freed? Freed and 
> allocated to something else?

See above. Also, use valgrind to catch these problems: it's a
fantastically wonderful tool for any serious C development.

> Validating the length might help limit the damage.

In the cases you describe in this mail, it seems more likely to me that
it would paper over problems in such a way as to make them harder to
spot before they cause real problems; other detection measures such as
valgrind will be more effective. In many other cases, validating the
length is indeed the right thing to do.

That said, many good C programmers do use the assert() macro to document
assumptions in their code.

Cheers,

-- 
Colin Watson                                    [cjwatson at canonical.com]




More information about the ubuntu-users mailing list