views:

43

answers:

1

The following code snippet is from The Official GNOME 2 Developer's Guide:

GMemChunk my_chunk;
my_chunk = g_mem_chunk_new("My Chunk",
                           42,
                           42*16,
                           G_ALLOC_AND_FREE);
gchar *data[50000];
gint i;

/* allocate 40,000 atoms */
for(i = 0; i < 40000; i++)
{
   data[i] = g_mem_chunk_alloc(my_chunk);
}
  • Does this mean every atom is of 42 bytes, each "memory chunk" contains 42 16 atoms, and 40000/16=2500 memory chunks will be created when the above code is run?

  • Why are they using gchar* here? Does an implicit cast from gpointer (void*) to gchar* take place when data[i] = g_mem_chunk_alloc(my_chunk); is run?

  • If the above statement is true then each gchar* points to 42 bytes of memory. How do I access all the bytes of a particular atom, then? Will data[7]+41 be a usable memory location?


  • When I try to compile the code gcc produces this error message:

    error: storage size of ‘my_chunk’ isn’t known What's wrong?

+3  A: 

In order of your questions:

  • Each memory block contains 16 atoms, but other than that, yes.
  • Yes, void * can be implicitly converted to any other pointer type in C, and this is typically considered to be good C style. They are using gchar * here because they apparently want to treat each atom as an array of 42 gchars.
  • Yes, data[7][41] is the last accessible byte of the 8th atom.
  • The error is because the declaration of my_chunk is wrong (GMemChunk is an opaque type that shouldn't be directly instantiated in your code). The declaration should be:

    GMemChunk *my_chunk;

as per the signature of g_mem_chunk_new() and g_mem_chunk_alloc().

By the way, the Glib documentation states that the Chunk allocator is deprecated, and you should use the slice allocator instead.

caf