Log in

View Full Version : memory useage GLOBAL, LOCAL Variable with strings


hsd1234
June 18th, 2006, 21:22
hello

when Im learning C

"GLOBAL variables always keep its memory til program die

so dont make them everytime"

Im really dont understand where are the Strings initialized in functions?

usually they are called LOCAL VARIABLEs

there must be CERTAIN AREA to keep Strings to initial.

so I tested with VC 6.0(my friend compiled it)-I dont have VC compiler

check out source at
http://www.rafb.net/paste/results/VsixY748.html

and result at
www.5n5f.co.kr/oh/LocalVariable.gif

they are surly existed on CERTAIN MEMORY that called .rdata
(maybe VC named it)

yeah there must be CERTAIN AREA and local Strings DO EXIST in memory til PROGRAM terminated.

I think so. hows other guys?

L. Spiro
June 18th, 2006, 23:48
Local variables exist within the stack space of the function in which they are declared.
That means their addresses are on the stack, which means the same addresses can be reused later by other functions, hence the livelihood of local variables is strictly within the scope of the function.

When you create a variable, you have the option of initializing it to some value.
If you initialize it to any built-in data type, for example a float, integer, character, or short constant:
float fPI = 3.14159f;
Then the compiler will generate a single instruction to write the floating-point representation of 3.14159 to the address on the stack where fPI exists.
Because single instructions themselves are capable of holding the “3.14159” constant, you won’t find backups of these values in the rdata section where you’re finding these strings.

So, what about more complex data types, such as your strings?
There is no instruction to write “AAAAAAAAAAAAAAAAAAAAA…” to an address.
Instead, the compiler creates the strings in the rdata section where you see them and then generates code to copy from that location to the location on the stack where your local is.
So, yes, there will be a backup there that exists for the life of your program.
But does this mean it is the same as declaring it as a global?
No.
If you declare two strings the same way in two different functions, the compiler doesn’t need to store two copies of the string globally. Each function gets its local copy from the same global location, which is in contrast with declaring two string variables as globals that are initialized to the same value.
If you declare them as global character arrays, they will both have their own copies, even if they are initialized to the same value.


The downside is stack space and execution speed.
Arrays declared on the stack, including character strings, use stack space, increasing the risk of stack overflow.
As well, the longer the string (or aggregate initializer), the longer it takes to copy from the back-up to the local.


L. Spiro

hsd1234
June 19th, 2006, 20:26
Im not sure 100% but you made me clear.

thank you very much