Reallocation of global variable in C

67 Views Asked by At

As I understand, when function is called from translation unit and this function uses global variable of this translation unit, variable address is unchangable. In case of recalling function from this module address does not change. How can I provide, every entering into module's function will update variable address? Is it real to allocate variable at the stack, not at the data segment?

For example, we have module MODULE and function FUNC of this module. Also we have MODULE2 and FUNC2 of this module. Variable VAR is global variable of MODULE.

  1. Call FUNC of MODULE
  2. Call FUNC2 of MODULE2
  3. Call FUNC of MODULE. How can I provide to reallocate VARIABLE location in every entering into MODULE (actually every FUNC calling)?
2

There are 2 best solutions below

0
Ted Lyngmo On

How can I provide, every entering into module's function will update variable address?

I take it as you wish for each translation unit to have its own instance of this global variable.

If so, declare it static in a header file that is included by all .c files that needs the variable and pass a pointer to the variable to the functions that are supposed to use it.

0
Luis Colorado On

IMHO, you are talking about calling a function, let's say f(), when f() calls g(), and at some point, g() calls again f() (what is called a recursive call)

If that's the problem, you have to declare your variable as local to the function. All variables in the inside of the external block (pair of curly brackets) are local (except if declared as static in which case they are global to the program, but not seen outside of the scope of the function block) and as local, they are reinstated (reallocated in a new stack frame) when the function is called (normally or recursively) so you have nothing to do, but declare the variables of interest as local, inside the function.

I'm not sure if this answers your question because you have given poor details to describe how will you be using the variables.

One function that has only automatic variables (variables that are created on entry and freed on return from the function) and has no global variables is called reentrant. This means the function can be called again while in the middle of its execution, of even worse, from two different threads of the same program.