Forum Menu




 


Log in Problems?
New User? Sign Up!
AVR Freaks Forum Index

Post new topic   Reply to topic
View previous topic Printable version Log in to check your private messages View next topic
Author Message
hectorheadgear
PostPosted: Feb 02, 2012 - 04:10 PM
Wannabe


Joined: Nov 22, 2010
Posts: 60
Location: Riverside, CA, US

This is just an excersize in deeper understanding of the C language, avr-gcc compiler, and avr devices, I don't have an actual problem I'm trying to solve.

Let's say I have a for loop inside a function that is called from main.

Code:
for (int i = 0; i < 5; i++) // "magic" number for demonstration only

{
 blah();
}


So the scope of the int i is local to this for loop, and as soon as control breaks from the loop, that variable goes out of scope. But what really happens here in memory and what have you? Is it that all references to the variable are erased and the device pretends it never existed? Or is it held there for later access within it's scope, you just can't do anything with it outside of it's scope?
This function is called many times, so I'm re-declaring it every time this function is called. I'm just curious what that actually means inside the chip.
 
 View user's profile Send private message  
Reply with quote Back to top
glitch
PostPosted: Feb 02, 2012 - 04:17 PM
Raving lunatic


Joined: Jan 12, 2002
Posts: 7827
Location: Canada

nothing is erased, it is allocated on the stack [if it needs a physical location, otherwise it will just reside in a register]. Either way, once the scope ends the location is reclaimed, and will be over-written next time an object needs to allocate some space. So while your value may exist for some time after, there are no rules or guarantees as to how long, as such you must consider it to be gone the moment scope ends.
 
 View user's profile Send private message  
Reply with quote Back to top
clawson
PostPosted: Feb 02, 2012 - 04:37 PM
10k+ Postman


Joined: Jul 18, 2005
Posts: 62209
Location: (using avr-gcc in) Finchingfield, Essex, England

Quote:

it is allocated on the stack [if it needs a physical location, otherwise it will just reside in a register]

Note that the GCC optimiser is pretty aggressive and would likely only create i on the stack if it's switched off (-O0) for all others it's almost bound to be assigned to a register or registers - which raises the question: if it counts from 0 to 4 why "int" and not uint8_t?

BTW this creation of i within the for() is a C++/C99 addition. Standard C won't allow it but in effect it's not really any different to the scope of i in:
Code:
void fn(void) {
  int i;
  // do stuff
}

In that i is also an "automatic" which means it's automatically created on entry and released/destroyed on exit. Such variables are almost always created on the data stack by C compilers.

Once again the optimiser would just use a register here and not actually bother with messing about with the stack unless (a) the variable were "volatile" or (b) built -O0

_________________


Last edited by clawson on Feb 02, 2012 - 04:40 PM; edited 2 times in total
 
 View user's profile Send private message  
Reply with quote Back to top
JohanEkdahl
PostPosted: Feb 02, 2012 - 04:39 PM
10k+ Postman


Joined: Mar 27, 2002
Posts: 18515
Location: Lund, Sweden

Quote:

This function is called many times, so I'm re-declaring it every time this function is called. I'm just curious what that actually means inside the chip.

An increase of the stack pointer with the size of the allocated variable, if even that.

Automatic variables (ok lets call them "local variables" although that is hardly the correct term for them in C) are allocated on the stack. Every parameter and local variable pertaining to the curently executing instance of a function is gathered together on the stack in what we might cal a stack frame. It is this stack frame that the stack pointer points to.

And it might even be that the compiler decides to allocate a parameter or local variable in a register.

If the parameter/variable is on the stack the compiler generates code for indirect access through the SP. That is why you will see, in some disassembly (for a bogus machine I just made up) code like

Code:
MOV SP+4, RX   ; Move the local at offset 4 from the stack pointer to register X


If the parameter or local variable is allocated in a register to start with, then it becomes even simpler to deal with it.

When the variable goes out of scope the compiler simply stops generating code for accesses to it (for sure, if you tried to refer to it in source code you would get a compile time error.) The compiler is free to immediately reuse the memory or register for another variable. It can simply start generating code for that. It needs no deallocation or allocation. Simply reuse the memory for another thing. This is also why you as a programmer/coder is responsible for initializing local variables. The C does compiler not do it for you.

Caveat Emptor: The description above is nudged, smoothed and slightly abused re the realities (there are several!). It is "how it generally works". Yes, regardless of which actual compiler you refer to you can claim that my description is not absolutely correct.

Lastly, this is not so tightly coupled to just the C language, but holds for many compiled languages.
 
 View user's profile Send private message Visit poster's website 
Reply with quote Back to top
clawson
PostPosted: Feb 02, 2012 - 04:42 PM
10k+ Postman


Joined: Jul 18, 2005
Posts: 62209
Location: (using avr-gcc in) Finchingfield, Essex, England

Quote:

It is this stack frame that the stack pointer points to.

While created on the stack avr-gcc usually uses Y as the stack frame pointer during the execution of a function. So you are more likely to see:
Code:
MOV Y+4, RX ; Move the local at offset 4 from the stack pointer to register X

_________________
 
 View user's profile Send private message  
Reply with quote Back to top
hectorheadgear
PostPosted: Feb 02, 2012 - 06:12 PM
Wannabe


Joined: Nov 22, 2010
Posts: 60
Location: Riverside, CA, US

Thanks for the clarification. Correct me if my summary is wrong.

Using optimization, variables of limited scope (such as a loop index counter) are typically assigned to registers, and as soon as that variable goes out of scope, the chip says "I don't need to reserve that register any more" and continues on like nothing happened...sort of like when you turn 18, move out, and your parents turn your room into the home gym lol. It's yours until you leave, and your stuff will sit in there until they need the space, at which point they do what they want with it. Wink

Would that be a fair analogy?
BTW, I just tried to insert a smiley with the "smiles" button in the quick reply area, and a window popped up exclaiming "Hacking attempt 1..." admin, do you know about this?
 
 View user's profile Send private message  
Reply with quote Back to top
hectorheadgear
PostPosted: Feb 02, 2012 - 06:25 PM
Wannabe


Joined: Nov 22, 2010
Posts: 60
Location: Riverside, CA, US

Quote:
Automatic variables (ok lets call them "local variables" although that is hardly the correct term for them in C)


Johan, could you elaborate on the nomenclature of these variables briefly? All of my computer science classes were in C++, so I'm used to the syntax and terminology of that much more than with C.

What differentiates a local variable from an auto variable, and does that distinction exist in C++ as well?
 
 View user's profile Send private message  
Reply with quote Back to top
clawson
PostPosted: Feb 02, 2012 - 06:37 PM
10k+ Postman


Joined: Jul 18, 2005
Posts: 62209
Location: (using avr-gcc in) Finchingfield, Essex, England

Quote:

What differentiates a local variable from an auto variable, and does that distinction exist in C++ as well?

AFAIK they are just different names for the same thing. The word "automatic" is perhpas more often used as it says that they are automatically created (and destroyed) whereas globals and statics are assigned a fixed storage location when the program is first built/linked in either .data (if initialised) or .bss (if left to be 0 - which is guaranteed).

Wikipedia: http://en.wikipedia.org/wiki/Automatic_variable

says:
Quote:
The term local variable is usually synonymous with automatic variable, since these are the same thing in many programming languages.


Or to put it another way: http://en.wikipedia.org/wiki/Local_variable

says
Quote:
In most languages, local variables are automatic variables stored on the call stack directly.

_________________
 
 View user's profile Send private message  
Reply with quote Back to top
sternst
PostPosted: Feb 02, 2012 - 06:56 PM
Raving lunatic


Joined: Jul 23, 2001
Posts: 2437
Location: Osnabrueck, Germany

hectorheadgear wrote:
What differentiates a local variable from an auto variable, and does that distinction exist in C++ as well?
"local variable" describes the scope.
"automatic variable" describes the storage type.

They are often used interchangeably just because of the fact that local variables have most often auto storage. But keep in mind that there are also local variables with static storage.

_________________
Stefan Ernst
 
 View user's profile Send private message  
Reply with quote Back to top
clawson
PostPosted: Feb 02, 2012 - 07:02 PM
10k+ Postman


Joined: Jul 18, 2005
Posts: 62209
Location: (using avr-gcc in) Finchingfield, Essex, England

Quote:

But keep in mind that there are also local variables with static storage.

But only if the word "static" is involved Wink

_________________
 
 View user's profile Send private message  
Reply with quote Back to top
sternst
PostPosted: Feb 02, 2012 - 07:17 PM
Raving lunatic


Joined: Jul 23, 2001
Posts: 2437
Location: Osnabrueck, Germany

clawson wrote:
Quote:

But keep in mind that there are also local variables with static storage.

But only if the word "static" is involved Wink
Yes, but nevertheless it is a local variable. So to say "just different names for the same thing" isn't quite right. "auto" and "local" are simply two different properties of a variable which occur most often in conjunction.

_________________
Stefan Ernst
 
 View user's profile Send private message  
Reply with quote Back to top
SprinterSB
PostPosted: Feb 02, 2012 - 07:41 PM
Posting Freak


Joined: Dec 21, 2006
Posts: 1483
Location: Saar-Lor-Lux

sternst wrote:
"auto" and "local" are simply two different properties of a variable
Some like to use the wording "storage class" and "static storage" for the latter.

Objects in static storage never die and are initialized before main: either by means of special startup code or already initialized at load time. Here, s1, s2 and s3 are in static storage:
Code:
int s1;
static int s2;

int* f3()
{
    static int s3;

    return &s3;
}
Objects in static storage keep their value even if they are out if scope. Thus, it is legitimate to pass the address of s3 outside of f3 which would not be the case for an auto variable.
 
 View user's profile Send private message Visit poster's website 
Reply with quote Back to top
sternst
PostPosted: Feb 02, 2012 - 08:02 PM
Raving lunatic


Joined: Jul 23, 2001
Posts: 2437
Location: Osnabrueck, Germany

SprinterSB wrote:
sternst wrote:
"auto" and "local" are simply two different properties of a variable
Some like to use the wording "storage class" and "static storage" for the latter.
With "latter" you mean my "local"? Then I have to protest. Wink
"local" is the description of the scope. It has actually nothing to do with "auto", "static", or "storage class".

_________________
Stefan Ernst
 
 View user's profile Send private message  
Reply with quote Back to top
skeeve
PostPosted: Feb 02, 2012 - 08:08 PM
Raving lunatic


Joined: Oct 29, 2006
Posts: 2638


When an automatic variable goes out of scope,
there is no longer any valid method by which you could refer to it.
Its name is unavailable.
Its address is invalid.
On an AVR, dereferencing a pointer with a formerly valid address will get you something,
but not necessarily what you want.
On other platforms, there might no longer be any there there.
An attempt to dereference the pointer might result in a memory violation.

A static variable that goes out of scope still exists.
Its address will remain valid.

_________________
Michael Hennebry
Iluvatar is the better part of Valar.
 
 View user's profile Send private message  
Reply with quote Back to top
JohanEkdahl
PostPosted: Feb 02, 2012 - 09:03 PM
10k+ Postman


Joined: Mar 27, 2002
Posts: 18515
Location: Lund, Sweden

Hey guys, I'm supposed to be the one who is nitpickin'!

I thought I made it clear both that my use of "local" instead of "automatic" was not entirely correct. And that my stack framed variable access was made up for pedagogical purposes, rather than being technically correct re any specific compiler and/or CPU architecture.

Tough gang you are..

Very Happy
 
 View user's profile Send private message Visit poster's website 
Reply with quote Back to top
skeeve
PostPosted: Feb 02, 2012 - 10:30 PM
Raving lunatic


Joined: Oct 29, 2006
Posts: 2638


JohanEkdahl wrote:
Hey guys, I'm supposed to be the one who is nitpickin'!
'Twasn't the nits.
'Twas the clarity and the information density.
To add to the clarity: In the case of a recursive function,
each function may have its own distinct version of an automatic variable.
There are more theres there.
Quote:
I thought I made it clear both that my use of "local" instead of "automatic" was not entirely correct. And that my stack framed variable access was made up for pedagogical purposes, rather than being technically correct re any specific compiler and/or CPU architecture.

Tough gang you are..

Very Happy

_________________
Michael Hennebry
Iluvatar is the better part of Valar.
 
 View user's profile Send private message  
Reply with quote Back to top
SprinterSB
PostPosted: Feb 02, 2012 - 11:00 PM
Posting Freak


Joined: Dec 21, 2006
Posts: 1483
Location: Saar-Lor-Lux

sternst wrote:
With "latter" you mean my "local"?
Uaaah. I must have seen some fata morgana while I answered to your post... You are right, of course.
 
 View user's profile Send private message Visit poster's website 
Reply with quote Back to top
Display posts from previous:     
Jump to:  
All times are GMT + 1 Hour
Post new topic   Reply to topic
View previous topic Printable version Log in to check your private messages View next topic
Powered by PNphpBB2 © 2003-2006 The PNphpBB Group
Credits