Joined: 16 Apr 2008 Posts: 1 Location: South Africa
Posted: Wed Apr 16, 2008 9:05 pm Post subject: stack or heap?
I was looking at some code from the example code section: A GTK+ Clock Using g_timout_add (C and Libglade) and I see that the heap is used.
Code: (Plaintext)
1 2 3 4 5 6 7
gchar *str = g_new(gchar, 25); /* allocate 25 characters for time */
/* some code */
g_free(str); /* free memory*/
Why not use?
Code: (Plaintext)
1
gchar str[25];
My thinking is:
Use the stack whenever possible.
Use the stack if you know the size of the buffer at compile time.
Using the stack has the advantage of not having to worry freeing the allocated memory, this is automatically freed once the variable goes out of scope.
Use the heap if you only know the size of the buffer at run time.
If memory is critical use the heap instead of specifying maximum sized buffers.
The danger of using the heap is that you have to remember to free the allocated memory.