GTK+ Forums

Discussion forum for GTK+ and Programming. Ask questions, troubleshoot problems, view and post example code, or express your opinions.
It is currently Fri Oct 31, 2014 7:23 pm

All times are UTC




Post new topic Reply to topic  [ 2 posts ] 
Author Message
 Post subject: stack or heap?
PostPosted: Wed Apr 16, 2008 9:05 pm 
Offline

Joined: Wed Apr 16, 2008 8:25 pm
Posts: 1
Location: South Africa
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=]
gchar *str = g_new(gchar, 25); /* allocate 25 characters for time */

/* some code */

g_free(str); /* free memory*/
[/code]

Why not use?
[code=] gchar str[25];[/code]

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.


Top
 Profile  
 
 Post subject:
PostPosted: Tue May 06, 2008 7:25 pm 
Offline
Never Seen the Sunlight

Joined: Wed Sep 21, 2005 12:07 am
Posts: 563
Location: Portland, OR USA
Good tip. Thanks.

_________________
Micah Carrick - Forum Administrator
http://www.micahcarrick.com


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC


Who is online

Users browsing this forum: No registered users and 3 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group