Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS/COE 0449 (term 2174) Jarrett Billingsley

Similar presentations


Presentation on theme: "CS/COE 0449 (term 2174) Jarrett Billingsley"— Presentation transcript:

1 CS/COE 0449 (term 2174) Jarrett Billingsley
C – Memory management CS/COE 0449 (term 2174) Jarrett Billingsley

2 Class announcements Exam Thursday! Wheee!
Today's material will be on it. Don't ignore warnings in C. Most of the time, warnings are really programming errors. Use the -Werror (and -Wall if you like) options to gcc. Please stay safe. Keep a vigilant eye on those in power, especially those who ignore checks and balances. (This is a general rule, but...) If you are/know a noncitizen, please research your rights. Things may be getting scary. Value your safety over your degree. 1/24/2017 CS/COE term 2174

3 Regions of memory 1/24/2017 CS/COE term 2174

4 Two new worlds The static or global data segment holds global variables and constants (like strings, struct/array initializers, etc). Local variables end up.. where, again? Both local and global variables are automatically allocated for you by the compiler and the operating system. The heap is a programmer-managed area of memory which lets you create and destroy pieces of memory as you need them. This is a powerful ability! But with great power blah blah blah. BE CAREFUL. 1/24/2017 CS/COE term 2174

5 Trainwreck Physically, in actual memory, the stack and heap areas – which can both grow dynamically – are arranged like this in most architectures/OSes. (down and up in memory addresses.) As the stack needs more space, it grows down... ...and as the heap needs more space, it grows up. When they meet, the program is out of memory. But a good question to ask is... why? Why not have the stack grow up and the heap down? Why not have them grow outward from the center? Why not have them both grow up or down? Why have them in the same area of memory at all? 64-bit architectures win here! Stack Heap 1/24/2017 CS/COE term 2174

6 Scope vs. Lifetime 1/24/2017 CS/COE term 2174

7 Scope int x = 52; if(blah()) { int x = 104; // same name!
Scope is "where a symbol can be seen." C has three levels of scope: globals, static globals, and locals. The difference between static and non-static globals won't become apparent until later, but globals can be seen everywhere. Locals can only be seen until the end of the block in which they were declared. Locals can also shadow other locals, e.g. int x = 52; if(blah()) { int x = 104; // same name! printf("%d\n", x); // prints 104 } 1/24/2017 CS/COE term 2174

8 Lifetime Lifetime is a little more subtle... it's the time between when a piece of memory is created and destroyed. What do you think the lifetime of globals is? What about locals? This is precisely why it's invalid to return pointers to locals. The memory holding the locals is destroyed. We call the behavior of locals automatic lifetime. In fact there's an ancient keyword, auto, which is the counterpart of static. All local variables are auto. 1/24/2017 CS/COE term 2174

9 You're watching the Lifetime Channel
int glob = 0x910B; void main() { int m = 10; func(); } void func() { int f = 10; } lifetime of glob lifetime of m lifetime of f (starting) main running func running (exiting) time 1/24/2017 CS/COE term 2174

10 If only it were that simple
In this Java code, what happens to the Scanner object after blah returns? Scanner blah() { Scanner s = new Scanner("blerf.txt"); return s; } We have an object whose lifetime starts in blah but ends somewhere else. The Scanner object is a heap object, and they all work like this. Java has convenient facilities (garbage collection) to ensure your heap objects eventually disappear! You can probably guess how C differs. 1/24/2017 CS/COE term 2174

11 The Heap 1/24/2017 CS/COE term 2174

12 The functions int* arr = malloc(sizeof(int) * 20); free(arr);
The heap lets you allocate and deallocate blocks of memory of any size, and at any time. The heap functions are in <stdlib.h> To allocate memory, you use malloc: int* arr = malloc(sizeof(int) * 20); This allocates a 20-item int array on the heap! malloc takes the number of bytes to allocate and gives you a pointer to the newly-allocated memory. When you're done with that block of memory, you use free: free(arr); arr = NULL; // good practice 1/24/2017 CS/COE term 2174

13 The caveats while(1) malloc(1048576); If you do this:
Your program will run out of memory. You are entirely responsible for freeing every single piece of heap memory that you allocate when you are done using it. 1/24/2017 CS/COE term 2174

14 The caveats int* arr = malloc(sizeof(int) * 20); free(arr);
If you do this: int* arr = malloc(sizeof(int) * 20); free(arr); arr[0] = 1000; // hmmm? who knows what'll happen! (This is why I said it's good practice to NULL the pointer.) After you free heap memory, all pointers to it become invalid, and it's entirely your responsibility to never use them again. ALL pointers. So if multiple things point to this memory... oops. 1/24/2017 CS/COE term 2174

15 But it's so usefulllllll
1/24/2017 CS/COE term 2174

16 Heap arrays If you want to allocate an array on the heap, just multiply the size of the item type by the number of items you want. Since the[indexing operator] is just pointer arithmetic, it works fine with the pointer returned by malloc. You can even have arrays of arrays! These are different from the multidimensional array variables (like int mat[3][4]). In an array-of-arrays, each item in the first array is a pointer to another array. So for two dimensions you'd have int**. 1/24/2017 CS/COE term 2174

17 Pointers to structs typedef struct Link { struct Link* next;
The heap isn't the only time you'll need pointers to structs, but it's a common one. typedef struct Link { struct Link* next; int value; } Link; Link* list = malloc(sizeof(Link)); list->next = NULL; list->value = 10; what the hell is this? 1/24/2017 CS/COE term 2174

18 Oh, yeah. Link a = {NULL, 1}; a.value = 10; Link* p = &a;
For thoroughly ridiculous reasons, if you want to access the members of a struct through a struct pointer... you have to use -> instead of . Link a = {NULL, 1}; a.value = 10; Link* p = &a; p->value = 20; // why tho If a is a struct pointer, a->b is exactly equivalent to (*a).b (much like how a[b] is equivalent to *(a + b) ) 1/24/2017 CS/COE term 2174

19 VLAs and alloca() 1/24/2017 CS/COE term 2174

20 Variable-size convenience; automatic deletion!
More modern C code has access to two ways to allocate variable sized pieces of memory on the stack, instead of the heap. I've seen many of you do stuff like this: int len = strlen(str); char newArray[len]; // not a constant size! This is a C99 feature, called variable-length arrays (VLAs). C89 only allows array variables to have constant sizes. VLAs let you specify the size at runtime... but it's still on the stack! Which gives you automatic lifetime (sweet!). You can use em, I don't mind, but they can't be used in strict C89 mode. 1/24/2017 CS/COE term 2174

21 alloca() int* arr = alloca(sizeof(int) * 20);
The more general-purpose way to allocate memory on the stack is with the alloca function. It looks just like malloc: int* arr = alloca(sizeof(int) * 20); And just like VLAs, any memory allocated by alloca has automatic lifetime – it disappears with the local variables. So should you return this arr pointer? Well these are great! Why don't we use them all the time?! 1/24/2017 CS/COE term 2174

22 Watch out. On most systems, stack space is limited.
On unix systems like thoth, ulimit -s tells you the limit. On thoth, it's 10 MB. That ain't too big. Both VLAs and alloca have to obey this limit. In addition, alloca is not portable. Not all OSes/architectures support it! 1/24/2017 CS/COE term 2174

23 Command line arguments
1/24/2017 CS/COE term 2174

24 ARRAY OF ARRAYS AAA int main(int argc, char** argv)
You remember that dumb String[] args in Java? You can get the same thing in C: int main(int argc, char** argv) The names are an old convention for "argument count" and "argument value". Just remember they're in alphabetical order. argc tells you how many strings there are in argv. argv is an array of strings. The first string is always the name of the program itself. It's that simple. 1/24/2017 CS/COE term 2174


Download ppt "CS/COE 0449 (term 2174) Jarrett Billingsley"

Similar presentations


Ads by Google