Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Do local variables have stack-dynamic lifetime?

c programming lifetime stack unix

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 DarkLordCthulhu


    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 422 posts

Posted 25 January 2015 - 02:12 PM

I'm confused about this.  Is it that case that all local variables not allocated on the heap have stack-dynamic lifetime while global variables have static lifetime?  Is the data segment of the executable used only for global variables while local variables live and die on the program stack?  Or are variables local to the main() function static while variables local to loops are stack-dynamic?  Or is it some other scheme?  I noticed in writing a program that an uninitialized character array local to a for loop that I was using to buffer input had detritus from previous programs in it and was not properly null-terminated, suggesting that it was part of the stack.  In Unix, uninitialized variables declared in the bss segment of an executable are initialized to zero (though it is possible that it was indeed initialized to zero, since the variable in question is a pointer to the first array element, rather than any of the array elements themselves).  I hope I'm making sense here.

Programming is a journey, not a destination.

#2 dargueta


    I chown trolls.

  • Moderator
  • 4854 posts

Posted 26 January 2015 - 02:49 PM

It seems you're confusing several concepts.


1) The .data segment of an executable is for read-only data like string constants. For example, if somewhere in your program you have printf("Hello, World!\n") then the string "Hello, World!\n" would show up in your .data segment.


2) Local variables aren't allocated on the heap. They're always allocated on the stack, and will usually contain garbage when first instantiated. However, you can have a local pointer to something on the heap. The heap isn't guaranteed to be zeroed out when first created (and oftentimes isn't).


3) The .bss segment contains reserved space for statically-allocated variables, like globals or static local variables. This is guaranteed to be initialized to zeroes.

Edited by dargueta, 26 January 2015 - 02:50 PM.

sudo rm -rf / && echo $'Sanitize your inputs!'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download