/
C – Scope, Lifetime, C – Scope, Lifetime,

C – Scope, Lifetime, - PowerPoint Presentation

calandra-battersby
calandra-battersby . @calandra-battersby
Follow
342 views
Uploaded On 2019-11-28

C – Scope, Lifetime, - PPT Presentation

C Scope Lifetime and the Stack CSCOE 0449 Jarrett Billingsley Class announcements lab 3 is out project 1 is out CS449 2 More pointer stuff CS449 3 const pointers for any type T a const ID: 768397

int return function stack return int stack function char cs449 main lifetime memory variables func str pointer address variable

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "C – Scope, Lifetime," is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

C – Scope, Lifetime,and the Stack CS/COE 0449 Jarrett Billingsley

Class announcements lab 3 is out? project 1 is out? CS449 2

More pointer stuff CS449 3

const pointers for any type T , a const T * is a read-only pointer to a Tyou can read the data that it points to, but you can't write ityou can however change where the pointer points toconst char* s = "hello";s = "goodbye"; // fine!s[3] = 'x'; // COMPILER error!const pointers are used when you want a pointer, but you want to promise that you won't change the thing that it points to.e.g. strlen() takes a const char* - it reads from the string but will not modify it.see 6_const_ptrs.c CS449 (2184) 4

Pointer casting casts convert from one type to another, like so: ( type )value int a = 20, b = 25; double x = a / (double)b; // now it's 0.8you can cast pointers toofloat f = 3.567;int* p = (int*)&f; // p points to f...printf("%08x\n", *p); // interprets f as an int!the computer does not care what bits representthis kind of cast does not change anything in memory f is still there and it still holds 3.567 it only changes how we view that memorysee 6_ptr_casts.c (and the visualization linked below it) CS449 (2184) 5

The Stack!!! CS449 6

The flow of control when the caller calls a function, where do we go? when the callee's code is finished, where do we go? CS449 7 void fork() { knife(); spoon++;}void knife() { spork++; spatula--;}callercallee

What's the stack? it's an area of memory provided to your program by the OS when your program starts, it's already therethe stack holds information about function calls. it's not a strict stack you can read and write any part of it but it grows and shrinks like a stackand we use "push" and "pop" to describe thateach program* gets one stackcause only one function is running at a timeCS4498MemoryStack

Activation records (ARs) when a function is called, a bunch of data is pushed onto the stack this is the call's activation record (or "stack frame") it contains local variables (including arguments) and the return addressCS4499int main() { int x, y; char buf[5]; return 0;}main's callerreturn addressxybuf[5] garbage main's AR Stack

The low-level layout each variable ( including array variables) gets enough bytes in the AR to hold its value where the variable is located is up to the compiler CS449 10 int x; char arr[3];short y;AddrValued02fd02ed02dd02creturn d02b d02a d029 d028 d027 d026 y d025 d024 d023 d022 d021 d020 x d01f d01e d01d arr d01c d01b d01a d019 d018 when I compiled this on thoth , this is the arrangement I got: sizeof ( int ) == 4 , so x gets 4 bytes sizeof ( arr ) == 3 , so it gets 3 bytes sizezof (short) == 2 , so.. yeah but what's all that grey space? idk lol, compiler does what it wants YOU DON'T NEED TO KNOW THE LOW-LEVEL LAYOUT!

Call = push, return = pop (animated) the stack grows when we call a function and shrinks when it exits CS449 11 main's caller return address x return addressptrreturn addressmainforkknife int main() { int x; fork(&x); return 0 ; } void fork( int * ptr ) { * ptr = knife(); } int knife() { return 10; }

Recursive functions (animated) recursive functions work by using the call stack as an implicit stack data structure CS449 12 fact(5)'s caller return address x = 5 return addressx = 4fact(5)fact(4)int fact(int x) { if(x <= 2) { return x; } else { return x*fact(x – 1); } } return address x = 3 fact(3) return address x = 2 fact(2)

But they don't really go away. (animated) the stack is used constantly so it needs to be really fast so we implement it as a pointer the stack pointer ( sp)CS44913main's callerreturn addressargc = 1argv = ...garbagesppush AR: sp -= (size of AR) return address x = 10 y = 25 garbage pop AR: sp += (size of AR) but the AR's memory is still there. so if we call another function … this is where that garbage in uninitialized variables comes from! address 10 25 garbage return address a = 10 b = 25 c = 10905928 garbage

Don't return stack arrays. I think I showed this before "function returns address of local variable" when func () returns, what happened to its variables? you have no idea you now have an invalid pointer it points to who-knows-what it might crashit might expose secretswho knows!!CS44914int main() { char* str = func(); printf("%s\n", str); return 0;}char* func() { char str[10 ] = "hi there" ; char* dummy = str ; return dummy; }

Scope and Lifetime CS449 15

Scope scope is "where a name can be seen" C has three levels of scope CS449 16 one.c two.c globals can be seen by any function in any filestatic globals can be seen by any function in one file locals can be seen by one function int main() { int x; }

Global variables are terrible and you should almost never use them. almost any problem where you think you need one can be instead solved by using a local and passing by reference. there are legitimate uses for them, but … unless you are being forced to use them…avoid them.CS44917

Homestead (animated) every variable takes up space in memory memory is limited, and the "land" must be "bought and sold." CS449 18 int x int * p float f memory must be allocated : reserved for a variable and when no longer needed, deallocated : released for other use the language handles this process for you, for local and global variables.

Lifetime lifetime is a little more subtle than scope... it's the time between allocation and deallocation. it's how long a value is "available" or "valid." global variables last from program start to program exit local variables' lifetime starts at their declaration, and ends at the closing brace that encloses themthough the compiler kinda optimizes this and just does one allocation at function start and one at function returnCS44919

You're watching the Lifetime Channel int glob = 0x910B ; int main() { int m = 10; func(); return 0;}CS44920(starting) main runningfunc running main running (exiting) void func () { int f = 10 ; } time lifetime of glob lifetime of m lifetime of f

Ownership ownership answers the question: who is responsible for deallocating a piece of memory? or: how do we know when it's okay to deallocate memory? different languages deal with this in different ways. Java uses garbage collection to do a lot of this. C mostly sticks its fingers in its ears, goes "LA LA LA," and pretends the problem doesn't exist. locals and globals are easy:locals are owned by functionsso their memory is deallocated by the function that made them.globals are owned by the programso their memory is deallocated when the program ends.but…CS44921

If only it were that simple in this Java code: what is the scope of each variable?what is the object's lifetime? the allocation happens at new. but… where is it deallocated? when? by who?important: the variables s and t and the object they point to have separate lifetimes.CS44922public static void main(String[] args) { String s = func (); s = null ; } String func () { String t = new String( "hello" ); return t; }

Looking at this problem a different way what is happening here is a conflict between ownership and lifetime. the programmer wants the variable to live longer than the ownership will allow it. but in C, there's no way to "transfer" the ownership. Java sidesteps this problem: objects can have one or more owners , but if no one owns it, it is deallocated.that's GC, and next class!CS44923int main() { char* str = func(); printf("%s\n", str); return 0;}char* func() { char str[10] = "hi there" ; char * dummy = str ; return dummy; }