GTK+ Forums Forum Index GTK+ Forums
Discussion forum for GTK+ and Programming. Ask questions, troubleshoot problems, view and post example code, or express your opinions.
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

stack or heap?

 
Post new topic   Reply to topic    GTK+ Forums Forum Index -> GTK+ Programming
Author Message
wil



Joined: 16 Apr 2008
Posts: 1
Location: South Africa

PostPosted: Wed Apr 16, 2008 9:05 pm    Post subject: stack or heap? Reply with quote

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.
Back to top
Micah Carrick
Never Seen the Sunlight


Joined: 21 Sep 2005
Posts: 426
Location: Portland, OR USA

PostPosted: Tue May 06, 2008 7:25 pm    Post subject: Reply with quote

Good tip. Thanks.
Back to top
Display posts from previous:   
Post new topic   Reply to topic    GTK+ Forums Forum Index -> GTK+ Programming All times are GMT
Page 1 of 1

 


Powered by phpBB © 2001, 2005 phpBB Group
CodeBB 1.0 Beta 2
Protected by Anti-Spam ACP