CS/COE 0449 (term 2174) Jarrett Billingsley

Slides:



Advertisements
Similar presentations
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Advertisements

Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Memory Overview 4 major memory segments Key differences from Java
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Programs – Preprocessing, Compilation and Linking
Memory Management.
Dynamic Allocation in C
Pointers to pointers & multi-dimensional arrays
Object Lifetime and Pointers
Dynamic Storage Allocation
EGR 2261 Unit 11 Pointers and Dynamic Variables
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
The Machine Model Memory
Chapter 6 CS 3370 – C++ Functions.
Overview 4 major memory segments Key differences from Java stack
C Primer.
CS/COE 0449 (term 2174) Jarrett Billingsley
CSE 374 Programming Concepts & Tools
CSE 451 C refresher.
Motivation and Overview
CSE 303 Concepts and Tools for Software Development
CNIT 133 Interactive Web Pags – JavaScript and AJAX
Pointers and Memory Overview
Checking Memory Management
CS/COE 0449 (term 2174) Jarrett Billingsley
CSCI206 - Computer Organization & Programming
Pointers and References
This pointer, Dynamic memory allocation, Constructors and Destructor
Pointers and Dynamic Variables
Advanced Programming Behnam Hatami Fall 2017.
CSC 253 Lecture 8.
C – Structs, Unions, Enums, Typedefs
C – Scope, Lifetime, and the Stack
Object Oriented Programming COP3330 / CGS5409
CS/COE 0449 Jarrett Billingsley
CSC 253 Lecture 8.
Overview 4 major memory segments Key differences from Java stack
CS 0449 Jarrett Billingsley
Pointers, Dynamic Data, and Reference Types
Built-In (a.k.a. Native) Types in C++
Dynamic Memory Allocation
Memory Allocation CS 217.
Given the code to the left:
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory A whole heap of fun….
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chien-Chung Shen CIS/UD
Pointers and Arrays Beyond Chapter 16
Arrays an array of 5 ints is filled with 3,2,4,1,7
Dynamic Memory A whole heap of fun….
Dynamic Memory.
C Programming - Lecture 5
Pointers and References
15213 C Primer 17 September 2002.
Pointers, Dynamic Data, and Reference Types
Classes and Objects Object Creation
SPL – PS2 C++ Memory Handling.
CSE 303 Concepts and Tools for Software Development
CS/COE 0449 Jarrett Billingsley
Presentation transcript:

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

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 0449 term 2174

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

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 0449 term 2174

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 0449 term 2174

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

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 0449 term 2174

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 0449 term 2174

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 0449 term 2174

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 0449 term 2174

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

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 0449 term 2174

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 0449 term 2174

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 0449 term 2174

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

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 0449 term 2174

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 0449 term 2174

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 0449 term 2174

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

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 0449 term 2174

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 0449 term 2174

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 0449 term 2174

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

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 0449 term 2174