C / Glib Strings to be freed by the caller

I use glib,
it has many functions that return strings that should be freed.

Can I pass these functions to other functions?

Example: function1 returns a string that should be freed for the caller. function2 returns a pointer to a string that should also be freed.

gchar *string = function2(function1("something"));
g_free (string);

How do I free the line returned by function1? It's necessary?

Thank you very much
and sorry for my english

+3
source share
3 answers

, , function1. , : -

gchar* temp = function1("something");
gchar* string = function2(temp);
g_free(temp);
g_free(string);
+6

:

gchar *string = function2(function1("something"));
g_free (string);

function1(). . , , , :

gchar *temp, *string;
temp = function1("something");
string = function2(temp);
g_free(temp);
temp = NULL;
g_free(string);

, , , function1() , , , (- , , free() d).

- function2():

gchar *function2_wrapper(gchar *c)
{
    gchar *ret = function2(c);
    free(c);
    return ret;
}

gchar *string = function2_wrapper(function1("something"));

, , , , , , , , , , , double- free() , ,

+3

, , @DaveRigby , , function1(), . , !

glib, g_string_append() function1(), . , .

,

GString *s = g_string_new("foo");

"http://foo/bar", :

s = g_string_prepend(g_string_append(s, "/bar"), "http://");
use_my_string(s);
g_string_free(s);

, , , . GString . .

+1

Source: https://habr.com/ru/post/1715477/


All Articles