-1

i know that heap is used in case of dynamic memory allocation otherwise stack is used. i have tried Difference between static memory allocation and dynamic memory allocation i know the difference but confusion is about their lifetimes.

Community
  • 1
  • 1
  • 3
    What kind of confusion? – Sourav Ghosh Sep 24 '15 at 14:11
  • 2
    they are all dead when the program terminates – Peter Miehle Sep 24 '15 at 14:12
  • 1
    Stack variables live until their scope ends (the closing `}` is reached from the point where they are declared). Dynamic variables live until you call `free` or `realloc` on them. That's about it - nothing else to understand. – Sergey Kalinichenko Sep 24 '15 at 14:14
  • what if we do not free the memory? @dasblinkenlight – Sakshi Rajput Sep 24 '15 at 14:16
  • 1
    @SakshiRajput Then you have a memory leak until your program exits, at which point the memory is freed by the execution environment. – Sergey Kalinichenko Sep 24 '15 at 14:21
  • 1
    @ericbn Err... no. You should actually read the question before suggesting duplicates. – Lundin Sep 24 '15 at 14:24
  • 1
    @dasblinkenlight With all due respect -- *objects* are on the stack or heap, variables aren't. Variables have scope, objects have lifetime. – Peter - Reinstate Monica Sep 24 '15 at 14:53
  • @SakshiRajput If you do not free, the run time environment is in charge. Part of it is the C runtime library (which comes with the compiler), part is the operating system. Modern and common run times -- gcc on Linux, VS on Windows -- return the aplication's heap to the OS when an executable ends. Simpler run times may fail to do that so that your machine has less memory available. But note that no destructors will be called on heap objects if you don't free them which may be bad if they hold resources the OS doesn't know about. – Peter - Reinstate Monica Sep 24 '15 at 14:58
  • Contd... For example, files will be closed at program exit, but database connections probably not. – Peter - Reinstate Monica Sep 24 '15 at 14:58
  • 2
    Note that the accepted answer of the linked question [Difference between static memory allocation and dynamic memory allocation](http://stackoverflow.com/questions/8385322/difference-between-static-memory-allocation-and-dynamic-memory-allocation) is wrong because it confuses static and automatic storage. – dpi Sep 24 '15 at 14:58
  • @dasblinkenlight: Please dont compare stack with dynamic. this are 2 complete different principles. stack vs. heap is an design concept. And has in Theory nothing to do with the kind of storage duration chosen. Where there are 3 in plain C and afaik 4 in c++. so there are in c: static storage types, automatic stoare types (what you probably meant by stack variables) and allocated storage types. (which is in c++ named dynamic afaik). But please keep the names of theese topics seperated from each other. as they are 2 completly different things, albeit theese things are related. – dhein Sep 24 '15 at 15:15
  • John is the only one who got it right. There is a third static storage duration called "static". They last as long as the program and are associated with (file) global or static variables. – Peter - Reinstate Monica Sep 24 '15 at 15:16
  • @Zaibis Please don't confuse comments with answers. – Sergey Kalinichenko Sep 24 '15 at 15:17
  • 1
    @Zaibis As much as I am for exactness -- can you provide an example in C -- i.e. an implemenation -- where allocated objects are not on the heap and objects with automatic storage duration are not on the stack? If not, the terms are interchangeable for all ends and purposes. – Peter - Reinstate Monica Sep 24 '15 at 15:18
  • @PeterSchneider: Well I can't provide a concret example, but I could imagine cases where some optimizations detect that an object is allocated and freed in the same scope without beeing accessable outside of the scope what could make the compiler decide to not even allocate it at all and just put it on the stack. But at all this doesn't matter. I aggree that the concept of heap and stack works this way, BUT the concept is not part of the language. so one can't claim that "it works this way in C" since this is not mentioned by the c draft in any way. – dhein Sep 24 '15 at 21:52
  • @dasblinkenlight: Yeah, thats ok, but anyway it wouldn't hurt to not mix up this words. I simply wanted to clarify. – dhein Sep 25 '15 at 06:38
  • Thank you all. This was really helpful. It has cleared many of my concepts. – Sakshi Rajput Sep 25 '15 at 16:31

2 Answers2

10

First of all, stacks and heaps are implementation details (the words "stack" and "heap" do not appear anywhere in the C language standard). Instead, the standard talks about storage durations for objects (Section 6.2.4).

As of C2011, there are four storage durations: static, automatic, thread, and allocated.

Objects with static storage duration have lifetimes1 that extend over the lifetime of the program. That is, memory is set aside for them when the program is loaded, and that memory is released when the program exits. Objects declared at file scope (outside of any function) or with the static keyword have static storage duration. Storage for static objects is usually allocated from within the binary image itself (for ELF, this would include the .data, .rodata, and .bss sections); that is, something other than a stack or heap.

Objects with automatic storage duration have lifetimes that extend from the entry of the block in which they're created until the block exits2. If the block is entered recursively, a new object is created. Objects declared within a block without the static keyword have automatic storage duration. Objects with automatic storage duration are usually allocated from a runtime hardware stack, although not all architectures have a stack.

Objects with thread storage duration have lifetimes that extend over the execution of the thread for which they were created. Objects declared with the _Thread_local keyword have thread storage duration. I think thread-local objects are allocated in the same way as auto variables, but that may be wrong; I've never used C2011 native threading, so I can't say for sure.

Objects with allocated storage duration have lifetimes that extend from the time they are allocated with malloc, calloc, or realloc until they are explicitly deallocated with a call to free. Objects with allocated storage duration are usually allocated from the heap (although not all architectures will have a heap as such). Where things get confusing is distinguishing the allocated object from the object that points to it. Given the following code:

int *foo( void )
{
  int *bar = malloc( sizeof *bar * 10 );
  // do stuff with bar
  return bar;
}

void bletch( void )
{
  int *blurga = foo();
  // do stuff with blurga
  free( blurga );
}

We've allocated three objects. In the function foo, we allocate a pointer object (referred to by the variable bar) with automatic storage duration; its lifetime is the lifetime of the function foo. In the function bletch, we allocate another pointer object (referred to by the variable blurga) with automatic storage duration; its lifetime extends over the lifetime of the function bletch.

The third object is a buffer large enough to hold 10 int objects. Its lifetime extends from the malloc call in foo to the free call in bletch; its lifetime is not tied to the lifetime of any function or block.


1. The lifetime of an object is the time within a program's execution that storage is guaranteed to be reserved for that object. Note that the lifetime of an object is distinct from the scope of the identifier that refers to that object. Even though memory for the object may be allocated at block entry, the scope of the identifier that refers to it may be more limited.

Assume the following code:
void foo()
{
  printf( "entered foo\n" );
  int i = 0;
  while ( i < 10 )
    printf( "%d\n", i++ );
}
The scope of the variable i extends from the end of its declaration until the end of the block; however, the lifetime of the integer object i refers to extends from block entry until block exit.

2. In practice, most compilers will set aside storage for all block-scope variables at function entry, even though some may be local to a block within the function. However, it's best to assume that the lifetime of an auto object only extends to the block in which it is contained.
John Bode
  • 119,563
  • 19
  • 122
  • 198
  • Nice answer. For your suggestion that allocation for thread local would be similar to `auto`, no I don't think that one can say that, it is really something apart. They use memory that is set aside when the thread starts up and deleted when it ends. – Jens Gustedt Sep 24 '15 at 15:22
  • @JensGustedt: yeah, I've never played with `_Thread_local` objects, so I'm not sure how they're usually allocated. – John Bode Sep 24 '15 at 15:23
2

Stack variables have local scope, meaning they are only valid to de-reference within the pair of {} where they were declared. While a dynamically allocated variable is valid until the point where your program calls free().

A more correct name would be local variables, since local variables may also end up allocated in CPU registers and not always on the stack. Formally, they are called variables with automatic storage duration in the C standard, meaning that the compiler automatically decides which is the best place to allocate them at.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Hm. I did not know you could allocate variables. You can allocate memory or perhaps even objects though (although I would argue that you *create* objects, which is the two-stage process of providing memory and running a constructor). – Peter - Reinstate Monica Sep 24 '15 at 15:02
  • @PeterSchneider Thanks for the off-topic, non-constructive rant. I felt it really contributed something of great value to the site. – Lundin Sep 25 '15 at 06:18
  • Sorry if my comment made the impression of a rant. It was meant to be sincere, sober, constructive and on-topic. It is important to be exact when talking about lifetime/storage duration and scope. I just searched the standard (n1570 draft) for "variable". There is no formal definition of it. The word is rarely used in the sense of name+value, and then often in remarks. (It's used more often as an adjective for variable length arrays and argument lists). Wikipedia (I know) seems to say "name and changeable value". One certainly does not allocate the name, so that ... [to be ctd.] – Peter - Reinstate Monica Sep 25 '15 at 08:05
  • [...ctd] "allocated variable" seems a bit fuzzy to me. It seems clearer to distinguish between the identifier which has a scope and does not need allocation, and the memory/storage that holds the associated value, which does need allocation and has a "duration" or life time. No rant intended. I usually appreciate your contributions, of course. – Peter - Reinstate Monica Sep 25 '15 at 08:07
  • @PeterSchneider This answer was meant to address a programming beginner, not the C standard committee. Search the C standard for the definition of "pedagogy" and you will find that it isn't mentioned there either. – Lundin Sep 25 '15 at 09:23
  • The point was, it was not helpful for the beginner. Consider `{ int*p = malloc(sizeof(int)); }`. We have an identifier p with local scope, the value of p with automatic storage duration, and a memory location with dynamic storage duration which does not have a name. `p` is actually a "stack variable with local scope", but I bet you the OP has problems to get their head around all that. He would probably say "p is a dynamically allocated variable". Hey, there was a malloc! – Peter - Reinstate Monica Sep 25 '15 at 09:32