const gchar* vs gchar *

Derek Atkins derek at ihtfp.com
Sat Dec 22 07:25:01 EST 2012


In C it is not enforced, but if you have a const pointer the compiler will
complain if you pass it as an argument to a function expecting a non-const
pointer.

-derek

On Sat, December 22, 2012 7:14 am, Jethro Beekman wrote:
> They're definitely not equivalent. Specifically:
>
>> If varA is defined as a const gchar *, will the program automatically
>> free the
>> memory allocated with g_strdup ?
>
> No. If you use strdup (or malloc, etc.), you need to free the resulting
> pointer
> afterwards.
>
> const on a pointer just means that you shouldn't modify the memory that
> the
> pointer points to. This is more useful when you use string constants. In
> C, this
> isn't strictly enforced, but in C++ it is. See also
> http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html
> .
>
> Jethro
>
> On 22-12-12 12:51, 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
>>
> _______________________________________________
> gnucash-devel mailing list
> gnucash-devel at gnucash.org
> https://lists.gnucash.org/mailman/listinfo/gnucash-devel
>


-- 
       Derek Atkins                 617-623-3745
       derek at ihtfp.com             www.ihtfp.com
       Computer and Internet Security Consultant



More information about the gnucash-devel mailing list