On Tue, Jul 03, 2001 at 09:34:43AM +0000, Conor Daly wrote:
> > 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.
>> "if you know the length of the data pointed to by s"
>> Therin lies the rub. I'm trying to be general here so I don't know the
> length of the destination char *array* 's'. I can find out the length of the
> string *within* 's' using strlen() but I don't know of a function that will
> return the amount of memory *allocated* to 's'.
>> > or you could free it and use strdup2.
> This looks likely. so I use
>> foo.s = mystrdup2(foo.s, s2);
but you didn't free it first?
> where
>> char * mystrdup2(char *s1, char *s2) {
>> /* create a tmp string to hold 's1' while we free that */
> char *tmp;
>> /* take a copy of s1 */
> if( (tmp = strdup(s1)) == NULL) return(s1); /* we failed to make a copy so bail out */
>> /* then free it */
> free(s1);
>> /* now use strdup2() to concat the two strings */
> if( (s1 = strdup2(tmp, s2)) == NULL) {
> /* the copy failed so we want to return the original string unchanged.
> * Maybe we should think about some way for the caller to be told that
> * we couldn't do the requested job but if we return NULL, we've
> * destroyed the original string which might upset the user!
> */
> return(tmp);
> } else {
> /* free the tmp string */
> free(tmp);
> /* and return the new pointer to s1 */
> return(s1);
> }
>> }
what a bizzare way to accomplish that. i get the impression that you
think this function will be have this way:
/*
* string1 = mem location 100; mem loc 100 contains "abc\0"
* string2 = mem location 200; mem loc 200 contains "xyz\0"
*/
string12 = mystrdup(string1, string2)
/*
* string1 = mem loc 100; the contents of 100 are unpredictable
* string2 = mem location 200; mem loc 200 contains "xyz\0"
* string3 = mem location 300; mem loc 200 contains "abcxyz\0"
*/
note that string1 is now in an undefined state.
> All this depends on being able to do malloc and free stuff with bits of
> structs. Like:
>> struct foo {
> char *s;
> } foozle; /* to plageri[sz]e a term of Kevin's)
>> foozle.s = (char *) malloc( <number of chars required> * sizeof(char));
>> and
>> free(foozle.s);
yes, of course. you have to be able to manipulate them. foozle.s is
a char * and can be used like that wherever.
kevin
Maintained by the ILUG website team. The aim of Linux.ie is to
support and help commercial and private users of Linux in Ireland. You can
display ILUG news in your own webpages, read backend
information to find out how. Networking services kindly provided by HEAnet, server kindly donated by
Dell. Linux is a trademark of Linus Torvalds,
used with permission. No penguins were harmed in the production or maintenance
of this highly praised website. Looking for the
Indian Linux Users' Group? Try here. If you've read all this and aren't a lawyer: you should be!