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
4216 atoms, and40000/16=2500memory 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]+41be 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?
In order of your questions:
void *can be implicitly converted to any other pointer type in C, and this is typically considered to be good C style. They are usinggchar *here because they apparently want to treat each atom as an array of 42gchars.data[7][41]is the last accessible byte of the 8th atom.The error is because the declaration of
my_chunkis wrong (GMemChunkis 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()andg_mem_chunk_alloc().By the way, the Glib documentation states that the Chunk allocator is deprecated, and you should use the slice allocator instead.