const gchar* vs gchar *

Geert Janssens janssens-geert at telenet.be
Sat Dec 22 07:50:15 EST 2012


Thanks Jethro and Derek, that confirms my understanding of the matter.

I'll go fix some memory leaks now...

Geert

On 22-12-12 13:19, Derek Atkins wrote:
> Hi,
>
> No, they are not equivalent.
>
> The 'const' basically tells the compiler that the object is immutable.
> It's used in an argument to promise that the function will not modify the
> object.  It's used in a return value to say that the caller may not modify
> or free the object because the callee will free it later.
>
> So no, your second function will have a memory leak, because g_strdup is
> expecting the caller to free the object.
>
> -derek
>
> On Sat, December 22, 2012 6:51 am, Geert Janssens wrote:
>> And now a question to show that I never had a formal c/c++ education.
>>
>> Are the below functions equivalent ?
>>
>> void funcA ()
>> {
>>       gchar *varA = g_strdup ("Test");
>>       <do something with a>
>>      g_free (varA);
>> }
>>
>> and
>>
>>
>> void funcA ()
>> {
>>       const gchar *varA = g_strdup ("Test");
>>       <do something with a>
>> }
>>
>> I'm mostly wondering if the second function would have a memory leak or
>> not. If varA is defined as a const gchar *, will the program
>> automatically free the memory allocated with g_strdup ?
>>
>> I don't expect so, but I'm seeing mixed uses in GnuCash and want to
>> determine for once and for all what is the proper way to handle this.
>>
>> Geert
>> _______________________________________________
>> gnucash-devel mailing list
>> gnucash-devel at gnucash.org
>> https://lists.gnucash.org/mailman/listinfo/gnucash-devel
>>
>



More information about the gnucash-devel mailing list