Re: g_strstrip question.
- From: TP Muller <tpm01 aber ac uk>
- To: gtk_list gtk gtk <gtk-app-devel-list gnome org>
- Subject: Re: g_strstrip question.
- Date: Fri, 6 Dec 2002 00:30:40 +0000
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
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]