[ILUG] C string concat question revisited
kevin lyda
kevin at suberic.net
Tue Jul 3 10:03:23 IST 2001
On Tue, Jul 03, 2001 at 08:38:50AM +0000, Conor Daly wrote:
> On Fri, May 04, 2001 at 01:11:07PM +0100 or thereabouts, kevin lyda wrote:
> > #define STRSIZE 80
> > char *
> > strdup2(char *s1, char *s2)
> > {
> > char *s;
> >
> > if ((s=(char *)malloc(STRSIZE + 1)) == NULL) {
> > return NULL;
> > }
> > /* the following initialises the string. s[0]=0;s[STRSIZE]=0; *
> > * would work too. */
> > memset(s, 0, STRSIZE + 1);
> > /* from here on in we don't let str* routines near s[STRSIZE] *
> > * so we know it will stay 0. */
> > strncpy(s, s1, STRSIZE);
> > strncat(s, s2, STRSIZE - strlen(s));
> > return s;
> > }
> >
> > strlen works by counting chars until it reaches '\0'. therefore don't use
> > it if you're not sure the string is null terminated.
> > sizeof(char) is not required.
well, i left some thoughts out. all the str* routines assume strings are
nul (not NULL) terminated. a more dynamic version would malloc a char *
of strlen(s1) + strlen(s2) + 1;
> Some while back, Kevin posted the above which allocates *new* memory for a
> string s which contains s1 and s2 (useage: s = strdup2(s1, s2); ).
> Now, I have a string struct.s which, as the name suggests, is part of an
> already allocated struct. If I want to set *that* to contain s1 and s2, can
> I use the above ( struct.s = strdup2(s1, s2); ) or do I just use strncpy()
> and strncat()?
so how is it defined? if it's
struct foo {
char s[123];
};
then no, the memory is already allocated. in fact using strdup2 would
be an error. otoh, if it is defined as:
struct foo {
char *s;
};
then the answer is "it depends." if that element of the struct is already
pointing at a string, you could use strncpy (if you know the length of
the data pointed to by s). or you could free it and use strdup2.
kevin
More information about the ILUG
mailing list