Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Unused Static Stack Varibles

Name: Anonymous 2009-10-31 1:48

Hey /prog/,

In C, are variables located in the stack recycled/freed when they are no longer needed? I suppose that this depends on the compiler, but does anyone know if GCC does this?

To be a little clearer, let's say I have these two translation units...

main.c/.h
settings.c/.h

main() calls the function get_settings() (located in settings.c) which will fill the variables (located in main.c) with data read from a file and then returns.

Since there is no longer any purpose for the staic variables declared in settings.c, are they freed once get_settings() returns?

Name: Anonymous 2009-10-31 2:42

Local variables of limited extent(scope) are subject to register allocation in most sane compilers, and when a register or stack location which was asseigned to a variable which is no longer needed, that space can be reallocated to another variable. Any serious compiler does this, and I've examined plenty of disassemblies of compiled C programs which show the same register used for the different variables in different places in the function, this also applies to locations on the stack.

While the ways in which each compiler does register allocation may be different, you should know that once a variable is out of scope, its location in memory/regs may become used by something else.

Name: Anonymous 2009-10-31 3:30

>>10
You'll have to consult your compiler's documentation for that.
Some compilers provide special declarations for such things, but first it might be better to just let the compiler perform register allocation by itself. What I said applies to variables, but you seem to mention functions. Functions are static pieces of code, and unless you're dynamically compiling function objects (for example Common Lisp has this, as well as some of the popular virtual machine based JIT engines do, but in less documented ways) and those function objects are treated as regular data that can be deallocated or garbage collected, then no. Unless you plan on allocating the code for your function dynamically and writing it there then freeing it, however for most normal C programs, code is allocated statically in the code section of your executable and stays there for the entire duration of the program. You could of course remove the code contained the function, but there is little use for doing that, as the space might not be easy to be reused for other things. The only reason people even do that is for crappy anti-reverse engineering tricks, which are way too futile.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List