const gchar* vs gchar *

Christian Stimming christian at cstimming.de
Sat Dec 22 16:17:12 EST 2012


I think the main source of misunderstanding is that in C, the compiler 
functionally doesn't make any difference between a const and a non-const 
pointer (except for the warning messages).

This is fundamentally different in C++, where due to argument overloading 
different functions might be called for const vs. non-const pointer arguments. 
But in C, basically a pointer is a pointer and that's it. There is no special 
behaviour for a non-const pointer vs. a const pointer in the C language.

The main advantage of using const pointers in general and writing const-
correct code is in its communication for the other programmers: The 
programmers should understand a const pointer as being immutable (i.e. the 
pointed-to object shouldn't have its state changed), and continue to use it 
this way. 

Regards,

Christian


Am Samstag, 22. Dezember 2012, 07:19:55 schrieb Derek Atkins:
> 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