Re: how to replace a substring in a string using C?



On Sun, 30 Oct 2005 21:46:46 +0100, Skarmander wrote:

> Netocrat wrote:
> <snip>
>> char *replace(const char *s, const char *old, const char *new)
>> {
> <snip>
>> ret = malloc(i + count * (newlen - oldlen));
>> if (ret == NULL)
>> exit(EXIT_FAILURE);
>
> Whoa, what's this? Just return NULL. It's massively rude to terminate
> the program in a function like this. It's *likely* the caller can't
> respond to out-of-memory either (and won't check for it if they're
> sloppy), but making the decision here is silly.

In a generic library function I agree 100%. When it's part of a specific
simple application, a policy to abort on memory failure isn't
unreasonable. The possibility did occur to me, and the reason I didn't
take it up is that it would have added extra lines to the (demonstration)
code. OTOH, this is intended to be a portable function, so your objection
is sound.

--
http://members.dodo.com.au/~netocrat
.