Re: [gtk-list] Re: potential problems with malloc/free vs. C++ new/delete ???



//
//> >   gchar **text;
//> >   text = new gchar*[8];
//> >   for (i=0; i<8; i++) {
//> >     text[i] = new char[100];
//> >   }
//> >         // set values of text[i]
//> >   gtk_clist_insert(clist, location, text);
//> 
//> > Should I instead be using malloc and free (or the glib wrappers) for
//> > any allocation for gtk even though my program has to use new and
//> > delete for the C++ class alocations?
//> 
//> If there already isn't, there should be a gtk_alloc/gtk_free pair that
//> you should use for any allocations that gtk will use, and for any
//> deallocations of gtk-allocated memory you will do. This is similar to
//> Xt's XtMalloc and XtFree, which merely wrap malloc/free. This way, there
//> is no question as to which api to use.
//> 
//> In the time being, if gtk uses malloc/free then you should do so as well
//> for gtk-related memory as above. It's best not to take chances!
//
//Ok so, I should probably change those "new"s to "malloc" or the glib
//wrapper version.

Right. And if you (or gtk) uses g_free on those pointers, you should be using 
g_malloc or g_new to allocate them.

Without digging into the gtk+ sources I can't say, but it would seem likely 
that gtk_clist_insert copies the strings you give it with g_strdup or some 
such. If that is the case, you'd have to free the stuff you allocate.

//For some reason I was also thinking that I read a program should
//either exclusively call new/delete or free/malloc, but clearly that
//can't be true or any mixture of C/C++ code would not work.

No; AFAIK you can mix new/delete and malloc/free in a program, you just can't 
mix them on one and the same pointer. Allocated with new? Then free with 
delete. Allocated with malloc? Then free with free.

Similarly, then: Allocated with g_malloc? Then free with g_free.

//Thanks,
//Dave
//dreed@capital.edu

Good luck,

Johannes.
--
One standard to rule them all, one standard to find them,
One standard to bring them all, and in darkness bind them.
In the land of Microsoft, where Shadows lie.

Visually inspecting visual programming languages.




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