From: Kenn Humborg (kenn at domain bluetree.ie)
Date: Wed 02 May 2001 - 18:09:46 IST
> Looking for a simple way to cat two strings into a third.
>
> I had the following in my code
>
> msg = strdup(strcat(strvar1, strvar2));
>
> What happens here is the strvar2 is concatinated to strvar1 and a
> pointer to strvar1 is returned to strdup which allocates memeory for the
> char *message variable.
And you are, of course, sure that the memory allocated to strvar1
has enough space for strvar2? And this is consipicously commented
in the source code so that the next guy doesn't break it (or, worse
still, use the same code elsewhere without ensuring this)?
And you'll check that strdup() doesn't return NULL?
> What I want is that functionality without strvar1 being modified. I
> would rather not have to create my own buffer and do it over two lines.
See, it's more than just a one-liner in any case... Now stop
being lazy and write _good_ code as opposed to _cute_ code
(which is very often broken, fragile, unmaintainable or downright
insecure):
msg = malloc(strlen(strvar1) + strlen(strvar2) + 1);
if (msg == NULL) {
/* argh */
} else {
strcpy(msg, strvar1);
strcat(msg, strvar2);
}
> I thought this was interesting as I couldn't see and alternative to
> strcat. Hope someone else can.
Later,
Kenn
This archive was generated by hypermail 2.1.6 : Thu 06 Feb 2003 - 13:10:09 GMT