Question

I am reading the concept of language ch 5 and find that

static's disadvantage : subprograms cannot share same storage.

stack-dynamic's advantage : without recursion, it is not without merit subprograms can share the same memory space for theirs locals.

and I think that due to static bound from begin to terminal, all subprogram should can see it and use

it

like the code I test

#include<iostream>
static int test = 0;

void func1(){ cout << test++ << endl;}
void func2(){ cout << test++ << endl;}
int main(){
    func1();
    func2();
}

and stack-dynamic allocation each time execute the function, like being push to stack(LIFO), so they

are in different momory space.

I don't know where is the error in my thought?

Thx in advance.

Was it helpful?

Solution

You program runs in a dedicated memory space. Static variables have global scope. Given that, I suppose "Subprograms cannot share same storage" means that static variable is instantiated only once and it's the same object during the entire lifetime of the program. This has several consequences:

  1. If your independent functions need storage as part of their execution, they shouldn't address the same static variables because they will affect the other functions using the same variables.
  2. If your functions can run in parallel (e.g. on several processors) and they address same static variables, these variable become a shared resource, meaning it must be protected against parallel access (which can corrupt the data and result in incorrect behavior).

Dynamically allocated/stack variables use the same memory space in which the program runs, but they can be instantiated many times, and the instances are independent of each other. E.g., if stack variable is defined inside a function, it's allocated upon function entry and released upon function exit. If the function is entered again, new variable will be created. It's same memory space, but different stack frame in this space.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top