MJL <ma**@affordablemedicalsoftware.com> wrote:
I am working on a small project that involves the manipulation of
dynamically allocated memory for strings. I was wondering why the
string.h functions are the way they are and why not as follows:
mystrcat(char** s1,char** s2);
where s1's memory allocation can now be handled inside of the function
and s2 can be freed and pointed to NULL inside the function.
Probably because such functions wouldn't be of general usefulness
and also would open up some nasty cans of worms. Take for example
the string pointed to by s2. There's nothing that would tell you
within your function that this string is actually pointing to
malloc()ed memory - it could also be a pointer to a string literal
or a char array. In that case you wouldn't be able to call free()
on it. Moreove, there are lots of cases where you don't want to
free() the source string.
The same problem would exist for s1. It could also be a pointer
to a char array. And you wouldn't even have any information how
much memory s1 is already pointing to. So how do you decide if
you can realloc() memory at all and if yes if you need to? More-
over, the caller would have to be aware that the address of s1
can change and if there are several other pointers around
pointing to the original string all of them would have to be
updated.
All in all I would say that you gain only a minimal amount in
functionality while making it rather difficult to use that kind
of functions correctly (since they can't be used with all kinds
of strings but only those for which memory has been obtained
dynamically). So they may be very useful for the project of yours
where you know exactly what you do but as general purpose
functions there would be much too many pitfalls the casual user
would have to be aware of.
Regards, Jens
--
\ Jens Thoms Toerring ___
Je***********@physik.fu-berlin.de
\__________________________
http://www.toerring.de