5

lets say I have a file test.c that contains:

char buffer1[1024];

int somefunction()
{
      char buffer2[1024];
      // do stuff
}

now I know buffer2 is allocated on the stack on the frame belonging to somefunction calls, but where is buffer1 allocated ?

Oren
  • 4,152
  • 3
  • 30
  • 37
  • 1
    Am I missing the beginning of line 1, or is `buffer1` really not statically allocated? –  Dec 24 '12 at 12:54
  • 6
    @H2CO3 any memory space which is neither automatically allocated (on the stack typically), or dynamically allocated (through malloc, etc.), is statically allocated. The `static` keyword is not necessary for a static allocation, it's rather a key to the compiler to indicate file scope (when used with the declaration of a program global as in this question's buffer1 case). – mah Dec 24 '12 at 13:01
  • 1
    @mah with C11 there is also thread storage duration. – effeffe Dec 24 '12 at 13:13
  • 1
    @effeffe thread local storage is just a specialized form of dynamic allocation (since the task control block is dynamically allocated when threads are created, and the TLS is associated with them). No? – mah Dec 24 '12 at 13:16
  • @mah I don't know how it works exactly, but I think you're right since there must be some kind of dynamic allocation for threads. But since their lifetime is different from static data and they could be not initialized at the beginning of the program, I pointed out that. – effeffe Dec 24 '12 at 13:34

3 Answers3

9

These variables are typically on BSS (variables which don't have explicit initialization in the source code, so they get the value 0 by default) or data segment (initialized datas). Here, buffer1 is uinitialized, so it will probably be allocated on BSS segment, which starts at the end of the data segment.

From bravegnu website:

enter image description here

md5
  • 23,373
  • 3
  • 44
  • 93
1

buffer1 has memory reserved in the static(bss/data) memory section of the program. That's where all statics and globals exist.

It is a third memory segment, like the stack and the heap.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

An array declared statically would have different storage specification from an array declared locally. As you said, a local array buffer2 will be (usually)created on stack while a static array buffer1 will be (usually)created on ./bss or ./data segments.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46