0

My impression from the gdk docs is that gdk_color_copy allocates memory:

Makes a copy of a color structure. The result must be freed using gdk_color_free().

The future-version gdk_rgba_copy clearly does:

A newly allocated GdkRGBA, with the same contents as rgba

Nevertheless I am encountering memory errors in my code with the following (my_struct.color is a GdkColor *, initialized to NULL):

if (my_struct.color != NULL) {
    gdk_color_free(my_struct.color);
}   
my_struct.color = gdk_color_copy(color);

And the following appears to work:

if (my_struct.color == NULL) {
    my_struct.color = malloc(sizeof(GdkColor));
}   
memcpy(my_struct.color, color, sizeof(GdkColor));
user3467349
  • 3,043
  • 4
  • 34
  • 61
  • 1
    can you clarify what you mean with "memory errors"? – wimh Apr 27 '15 at 18:27
  • Corruption, or invalid pointer free, or other stuff on program exit. – user3467349 Apr 27 '15 at 18:29
  • 1
    Mhmm, I think I know what's wrong. I was calling g_free in my finalize method instead of gdk_color_free - swapping those seems to fix it? Really not sure that was possible – user3467349 Apr 27 '15 at 18:36
  • Yes, you must always match allocators. Mixing and matching results in bugs like these. You can see the source to see what `gdk_color_free()` really does. – andlabs Apr 27 '15 at 21:19

1 Answers1

1

gdk_color_copy uses g_slice_new to allocate memory as can be seen in the source.

Using g_free instead of gdk_color_free or g_slice_free will cause errors. This can be verified by compiling with G_SLICE=always-malloc which will cause g_slice_new to use malloc calls instead and the corruptions will disappear.

user3467349
  • 3,043
  • 4
  • 34
  • 61