Re: a question about g_strconcat()



On Thu, Feb 28, 2013 at 2:22 PM, Cifer Lee <mantianyu gmail com> wrote:
first, I will show some lines.
[code]
gchar *str_sample = g_strconcat("I have a", "dream that", NULL);

str_sample = g_strconcat(str_sample, " one day", NULL);

Here is memory leak (leak the memory allocated by 1st g_strconcat()).


str_sample = g_strconcat(str_sample, " we can be friends.", NULL);

And here too (leak the memory allocated by 2nd g_strconcat())


// do some work with str_sample

g_free(str_sample);
[/code]

The simplest way to rewrite your code to not leak and keep similarity
is a use GString.

Your code (g_strconcat() + leak):
{
    gchar *str_sample = g_strconcat("I have a", "dream that", NULL);
    str_sample = g_strconcat(str_sample, " one day", NULL);
    str_sample = g_strconcat(str_sample, " we can be friends.", NULL);
    // do some work with str_sample
    g_free(str_sample);
}

Changed code (GString without leak):
{
    GString *str_sample = g_string_new(NULL);
    g_string_append(str_sample, "I have a");
    g_string_append(str_sample, "dream that");
    g_string_append(str_sample, " one day");
    g_string_append(str_sample, " we can be friends.");
    // do some work with str_sample->str
    g_string_free(str_sample, TRUE);
}

But see below, please!


if, for some reasons, I must call g_strconcat() three times, or in
concrete, I must follow some conditions to determine whether should I
concatenate each of the three phrases.... okay, actually, I am writing a
sql query phrase, like this:

if the parameter an_id is a empty string, then I will not append it to the
select phrase.

select * from a_table where 1=1 and `id`='an_id' and `name`='a_name'


Please!  Don't do that!  Do not build SQL queries in such way!  Step
left, step right -- and you have SQL injection or something even
worse!  All more or less sane databases support the prepared
statements and allow to bind variables.  I don't know what database
you are using and, therefore, unable give to you the exact names of
function.  Please, do not play with fire trying to build the whole SQL
statement with fully and properly quoted and substituted variables!
Use prepared statements instead!


actually, I have debug my program and find that each time the str_sample
variable has been assigned a different address. But I'm not sure the
internal mechanism of g_strconcat(), whether it apply for a totally new
space or a space that may overlap with the earlier applied space, if the
latter, then I can't free the earlier applied space, and I think it may
lead to memory leak.


-- 
Andrew W. Nosenko <andrew w nosenko gmail com>


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