Re: g_strstrip question.



--- TP Muller <tpm01 aber ac uk> wrote:
On Thursday 05 December 2002 21:41, Brett Nash wrote:

        If you have some string str1 which you need to free...
        char *str1;
        char *oldstr;
        /* Replace this with however str1 is allocated */
        str1 = g_strdup("Some random string");
        /* Save a copy */
        oldstr = str1;
        str1 = g_strstrip(str1);
         ...
        g_free(oldstr); /* str1 is now an invalid pointer */
        str1 = oldstr = NULL; /* sanity */

While this works fine, I don't think it's really necessary:

g_strstrip is defined like this:

#define g_strstrip( string )    g_strchomp (g_strchug (string))

g_strchug() will actually move the 'real' beginning of the string (ie. after 
skipping any leading spaces) forward. In other words: g_strchug() will return

exactly the same pointer address that you pass and shift the content:

gchar* g_strchug (gchar *string)
{
  guchar *start;
  g_return_val_if_fail (string != NULL, NULL);
  for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
    ;
  g_memmove (string, start, strlen ((gchar *) start) + 1);
  return string;
}

g_strchomp() 'cuts off' the string before any trailing spaces by inserting a 
NULL char.

The memory manager doesn't care much for the content of any allocated memory 
(ie. where the NULL character is in the string).


In other words:

   gchar *mystring = g_strdup ("     foooo    ");
   mystring = g_strstrip (mystring);
   g_print ("-->%s<---\n", mystring);
   g_free(mystring);

should be fine IMHO, in both glib-1.2 and glib-2.0.

Please correct me if I'm wrong.

Cheers
-Tim


  Tim,

 I think you have a good point. If - in fact - gstrstrip moves the contents of
the string to the original position of the pointer, the MM will use the info on
that pointer when it is time to free it. (I have not looked at the code closely
-- AND PROBABLY SHOULD HAVE --. ) I will take a look when I get a chance.

  Thank you for the input.

HArring.

 

__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]