CMSC 341 Lecture 2 Dynamic Memory and Pointers

Similar documents
CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

CMSC202 Computer Science II for Majors

CSC 1600 Memory Layout for Unix Processes"

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

o Code, executable, and process o Main memory vs. virtual memory

CS 11 C track: lecture 5

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING

EL2310 Scientific Programming

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Intermediate Programming, Spring 2017*

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

In Java we have the keyword null, which is the value of an uninitialized reference type

a data type is Types

Class Information ANNOUCEMENTS

377 Student Guide to C++

Variables, Memory and Pointers

Lecture Notes on Memory Layout

6.S096: Introduction to C/C++

Lecture 2, September 4

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS201- Introduction to Programming Current Quizzes

CA31-1K DIS. Pointers. TA: You Lu

Debugging (Part 2) 1

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CS558 Programming Languages

Dynamic memory allocation (malloc)

CS61, Fall 2012 Section 2 Notes

EE355 Lab 5 - The Files Are *In* the Computer

[0569] p 0318 garbage

Programs in memory. The layout of memory is roughly:

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Pointers and Memory Management

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Homework #3 CS2255 Fall 2012

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Dynamic Allocation of Memory

Praktische Aspekte der Informatik

Creating a String Data Type in C

CSCI-1200 Data Structures Fall 2015 Lecture 6 Pointers & Dynamic Memory

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Advances in Programming Languages: Regions

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

DEBUGGING: DYNAMIC PROGRAM ANALYSIS

Pointers review. int a = 5; int *ptr = &a; cout << *ptr;

CS 61c: Great Ideas in Computer Architecture

TI2725-C, C programming lab, course

Pointers and References

Memory and C++ Pointers

Dynamic Memory Management

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Princeton University Computer Science 217: Introduction to Programming Systems. Data Structures

Memory Management. CS449 Fall 2017

Dynamic Memory Allocation: Advanced Concepts

REFERENCES, POINTERS AND STRUCTS

CSC C69: OPERATING SYSTEMS

Lab 3. Pointers Programming Lab (Using C) XU Silei

Dynamic Memory Management

Dynamic Data Structures. CSCI 112: Programming in C

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

COMP 2355 Introduction to Systems Programming

Memory Analysis tools

Vector and Free Store (Pointers and Memory Allocation)

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Limitations of the stack

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CA341 - Comparative Programming Languages

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

Intermediate Programming, Spring 2017*

Dynamic Memory CMSC 104 Spring 2014, Section 02, Lecture 24 Jason Tang

CS61C : Machine Structures

CPSC 427: Object-Oriented Programming

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

ECE 15B COMPUTER ORGANIZATION

Chapter 17 vector and Free Store

Lecture 07 Debugging Programs with GDB

Pointers, Dynamic Data, and Reference Types

内存管理. Memory management

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

CS 103 Lab The Files are *In* the Computer

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

CS558 Programming Languages

Contents. 8-1 Copyright (c) N. Afshartous

Exam 3 Chapters 7 & 9

CS 161 Exam II Winter 2018 FORM 1

Key C Topics: Tutorial Pointers, Dynamic Memory allocation, Valgrind and Makefile CS370

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

CIS 190: C/C++ Programming. Lecture 2 Pointers and More

Dynamic Memory Management! Goals of this Lecture!

Programming Abstractions

Transcription:

CMSC 341 Lecture 2 Dynamic Memory and Pointers Park Sects. 01 & 02 Based on earlier course slides at UMBC

Today s Topics Stack vs Heap Allocating and freeing memory new and delete Memory Leaks Valgrind Pointers Dynamic Memory and Classes

Program Memory The memory a program uses is typically divided into four different areas: 1. The.text section, where the executable code sits in memory. 2. The.data/.bss area, where global variables are stored. 3. The stack, where parameters and local variables are allocated from. 4. The heap, where dynamically allocated variables are allocated from. From: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

.data vs. Heap.data/.bss contains variables that are global or static Things that exist over the entire lifetime of the program s execution.bss is for uninitialized data (technically, initialized to 0) The size of the data section is fixed Heap holds data that is dynamically allocated during execution The heap can grow and shrink during the life of the program

Stack vs Heap What is stored: Stack is used to store: Automatic variables: i.e., non-static local variables Function arguments Basically, the data relevant to a specific instance of a function call Allows recursion (since each new call pushes a new stack frame ) Heap stores things created with new or by calling malloc() Must be accessed through pointers

Stack vs Heap Space management: Stack space management is implicitly handled by the system/compiler: grows automatically, every time a nested function/method is called has an upper limit; heap growth must be requested When a function returns, the stack frame is deleted You might be still able to access it, but you should not! Heap space is managed by the programmer Memory allocated with new must be cleared with delete; and malloc() calls mush have matching free() Failing to free heap space when done causes memory leaks

Declaring Stack and Heap Variables Stack variable declaration What you ve been doing all along int counter; double scores[10]; (Note: static int foo would not be on the stack: it s in data section) Heap variable declaration Must use a pointer int *values = new int[numvals]; (a technical point: the new array is in the heap, but the pointer values is actually still a stack variable)

Allocating and Freeing Memory

new and delete Used to dynamically allocate and free memory on the heap new must be assigned to a pointer variable int *calendar = new int[12]; SomeClass *newitem = new SomeClass; delete releases memory previously allocated with new can only be used on pointer variables delete newitem; delete[] calendar;

Good Programming Practices C++ does not have garbage collection After memory has been freed, set the pointer equal to NULL Must be done after delete is called Why do this?

Memory Leaks Occur when data is allocated, but not freed Calling new over and over, but never delete Not freeing new memory before exiting a function Access to the previous memory is lost The location of that memory was overwritten Eventually the program runs out of memory, and the program will crash

Memory Leak Example int *arr, var = 1000; for (int i = 0; i < var; i++) { arr = new int[100000000]); } Heap arr?

Memory Leak Example int *arr, var = 1000; for (int i = 0; i < var; i++) { arr = new int[100000000]); } arr = new int[100000000] arr = new int[100000000] arr = new int[100000000] Heap arr = new int[100000000] arr = new int[100000000] arr arr = new int[100000000]

Memory Leak Example int *arr, var = 1000; for (int i = 0; i < var; i++) { arr = new int[100000000]); } arr = new int[100000000] arr = new int[100000000] arr = new int[100000000] Heap arr = new int[100000000] arr = new int[100000000] arr arr = new int[100000000]

Valgrind Assists with dynamic memory management Memory allocated using new And therefore on the heap Must compile with the -g flag (for debugging) Detects memory leaks and write errors Running valgrind significantly slows program down program to run on valgrind --leak-check=yes proj1 arg

Example valgrind Run Code #include <stdlib.h> void f(void) { int* x = malloc(10 * sizeof(int)); x[10] = 0; // problem 1: heap block overrun } // problem 2: memory leak--x not freed int main(void) { f(); return 0; } Please note: This is C code, not C++. Source: http://valgrind.org/docs/manual/quick-start.html/

Example valgrind Run Results 1 Describes problem 1 (heap block overrun) ==19182== Invalid write of size 4 ==19182== at 0x804838F: f (example.c:6) ==19182== by 0x80483AB: main (example.c:11) ==19182== Address 0x1BA45050 is 0 bytes after a block of size 40 alloc'd ==19182== at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130) ==19182== by 0x8048385: f (example.c:5) ==19182== by 0x80483AB: main (example.c:11) Source: http://valgrind.org/docs/manual/quick-start.html/

Example valgrind Run Results 1 Describes problem 1 (heap block overrun) ==19182== Invalid write of size 4 ==19182== at 0x804838F: f (example.c:6) ==19182== by 0x80483AB: main (example.c:11) ==19182== Address 0x1BA45050 is 0 bytes after a block of size 40 alloc'd ==19182== at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130) ==19182== by 0x8048385: f (example.c:5) ==19182== by 0x80483AB: main (example.c:11) Source: http://valgrind.org/docs/manual/quick-start.html/ First line: type of error Stack trace (read from bottom up)

Example valgrind Run Results 2 Describes problem 2 (memory leak) ==19182== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==19182== at 0x1B8FF5CD: malloc ==19182== by 0x8048385: f (a.c:5) ==19182== by 0x80483AB: main (a.c:11) Source: http://valgrind.org/docs/manual/quick-start.html/

Example valgrind Run Results 2 Describes problem 2 (memory leak) ==19182== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==19182== at 0x1B8FF5CD: malloc ==19182== by 0x8048385: f (a.c:5) ==19182== by 0x80483AB: main (a.c:11) First line: type of error Stack trace tells you where the leaked memory was allocated (in function f on line 5 of file a.c) Your program is definitely leaking memory! (May also see probably, possibly, or indirectly. ) Source: http://valgrind.org/docs/manual/quick-start.html/

Pointers: Quick Review (Not meant to teach you the concept from scratch!)

Pointers Used to point to locations in memory int x; int *xptr; x = 5; xptr = &x; /* xptr points to x */ *xptr = 6; /* x s value is 6 now */ Pointer type must match the type of the variable whose location in memory it points to

Pointers Ampersand Ampersand ( & ) returns the address of a variable Asterisk ( * ) dereferences a pointer to get to its value (also used when initially declaring a pointer) int x = 5, y = 7; int *varptr; varptr = &x; *varptr = 0; varptr = &y; x = *varptr;

Examples Ampersand and Asterisk int x = 5; int *xptr; [* used to declare ptr] xptr = &x; [& used to get address] *xptr = 10; [* used to get value] cout << &xptr; [& used to get address]

Examples Ampersand and Asterisk int x = 5; int *xptr; [* used to declare ptr] xptr = &x; [& used to get address] *xptr = 10; [* used to get value] cout << &xptr; [& used to get address]

Pointer Assignments Pointers can be assigned to one another using = int x = 5; int *xptr1 = &x; /* xptr1 points to address of x */ int *xptr2; /* uninitialized */ xptr2 = xptr1; /* xptr2 also points to address of x */ (*xptr2)++; /* x is 6 now */ (*xptr1)--; /* x is 5 again */

NULL Pointers NULL is a special value that does not point to any address in memory It is a non address Uninitialized pointers are like any new memory they can contain anything Setting a pointer to NULL will prevent accidentally accessing a garbage address (but dereferencing a null pointer will still give a segfault that s a Good Thing!)

Pointer Visualization Exercise int x = 5; int *xptr = &x; /* xptr points to x */ int y = *xptr; /* y s value is? */ variable name x xptr y memory address 0x7f96c 0x7f960 0x7f95c value 5 0x7f96c?

Pointer Visualization Exercise int x = 5; int *xptr = &x; /* xptr points to x */ int y = *xptr; /* y s value is? */ variable name x xptr y memory address 0x7f96c 0x7f960 0x7f95c value 5 0x7f96c?

Pointer Visualization Exercise int x = 5; int *xptr = &x; /* xptr points to x */ int y = *xptr; /* y s value is? */ variable name x xptr y memory address 0x7f96c 0x7f960 0x7f95c value 5 0x7f96c?

Pointer Visualization Exercise int x = 5; int *xptr = &x; /* xptr points to x */ int y = *xptr; /* y s value is? */ variable name x xptr y memory address 0x7f96c 0x7f960 0x7f95c value 5 0x7f96c?5

Pointers and Arrays Arrays are built by pointers Array name equivalent to address of first element char terry[6] = hello ;

Dynamic Memory and Classes 33

Dynamically Allocating Instances Stack: Date today; Heap: Date *todayptr = new Date(2016,2,7); In both cases, constructor called (different versions, though)

Dynamically Allocating Instances Stack: Date today; nothing handled for you Heap: Date *todayptr = new Date(2016,2,7); call delete and set pointer to NULL delete todayptr; todayptr = NULL; What to do when freeing memory?

Accessing Member Variables Objects/structs (non-dynamic) Use the dot notation today.m_day = 2; Heap (dynamic), or any other pointers Use the arrow notation todayptr->m_year = 2015; Shorthand for dereference and use dot (*todayptr).m_year = 2015;

Passing Class Instances Stack Normal variable; works as expected cout << x; Heap Need to dereference variable first cout << xptr; // prints address cout << *xptr; // prints value

Destructor All classes have a built-in destructors Created for you by C++ automatically Called when instance of class ceases to exist Explicit delete, or end of program (return 0) Classes can have member variables that are dynamically allocated Built-in destructors do not free dynamic memory! Must code one for the class yourself

Coding Destructors Named after class, and has no parameters In source (.cpp file) Student::~Student() { // free array of class name strings delete classlist; } In header (.h file) ~Student(); // denotes destructor

Calling Destructors Stack Student GV37486; Automatically called at end of scope (function); Heap Student *FY18223 = new Student(); Called only when memory is freed delete FY18223; // destructor called FY18223 = NULL;

Segmentation Fault FAQ What is a segmentation fault ( segfault )? It happens when you access a memory address that is not legal (i.e., not in one of: data, heap, or stack) Why is my program killed? The operating system shows no mercy (real answer: few other options) What causes a segfault? An erroneous pointer

Segmentation Fault FAQ (cont) Does a bad pointer always cause a segfault? No: if the bad pointer coincidentally points into some random-but-legal memory space, you will end up corrupting memory instead Will dereferencing a pointer after deleting what it is pointing to cause a segault? Not necessarily; in fact, usually no; that is why we always set it to NULL

Segmentation Fault FAQ (cont) Why do you say a segfault is a Good Thing? It s not good: just better than bad. Assuming you already have a bad pointer, would you rather: a) silently corrupt random memory; OR b) have your program admit it s broken, and allow GDB to say exactly where?