const gchar* vs gchar *

Jethro Beekman gnucash at jbeekman.nl
Sat Dec 22 07:14:07 EST 2012


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
> 


More information about the gnucash-devel mailing list