SPL – Practical Session 2 Topics: – C++ Memory Management – Pointers.

Slides:



Advertisements
Similar presentations
Chapter 17 vector and Free Store Bjarne Stroustrup
Advertisements

Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
SPL/2010 Pointers and Parameter Passing in C++ 1.
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:
SPL – Practical Session 2 Topics: – Makefile – C++ Memory Management – Pointers.
Informática II Prof. Dr. Gustavo Patiño MJ
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
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++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers. The structure of memory Computer memory is a linear sequence of addressable locations Addresses are numbered starting at zero In personal computers,
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
Pointers OVERVIEW.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Dynamic memory allocation and Pointers Lecture 4.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
System Programming Practical Session 7 C++ Memory Handling.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
P OINTERS A pointer is an address All data is stored in memory in some location that is indexed with an address Can refer to variables by name or by memory.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Memory-Related Perils and Pitfalls in C
Dynamic Allocation in C
CSC 533: Programming Languages Spring 2016
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
CSC 533: Programming Languages Spring 2015
Day 03 Introduction to C.
Day 03 Introduction to C.
SPL – Practical Session 2
Lecture 6 C++ Programming
Pointers, Dynamic Data, and Reference Types
C++ Pointers and Strings
C++ Pointers and Strings
Pointers, Dynamic Data, and Reference Types
CSC 533: Programming Languages Spring 2019
SPL – PS2 C++ Memory Handling.
Presentation transcript:

SPL – Practical Session 2 Topics: – C++ Memory Management – Pointers

C++ Memory Handling Memory Model, Pointers

Variables in C++ Memory System There are two "kinds" of memory available to a process: Stack: – Stores local variables of the function. – Removed once the function ends! Heap: – Contains dynamically allocated variables. – Stays once the function ends, unless cleared before! Read more:

Pointers A pointer is a variable that holds the address of some other variable. In Java, you can’t directly access the memory of such object! Only by reference. In C++, you can access them directly! Alter them any way you like, without any limitations! Benefit: More control than Java. Drawback: Memory leaks, Memory corruption. A 64-bit computer can address 2 64 bytes! Each memory cell is 1 byte. (byte-accessible machines – most of the machines today) Each pointer takes a static size of 4 bytes in a 32bit OS, and 8bytes in a 64bit OS. Pointers themselves are saved on the stack.

Java vs. C++ Java’s References String s = new String("a string"); – The value of the variable 's' is the location of the object on the heap, but we don’t have access to this value! You can not have a variable that 'points' to a primitive type String s = null; – means "I don't have the address of any meaningful data" C++ Pointers Have access to actual memory locations. Can point to anything! The null value in C++ is the number 0 (memory address 0).

Pointers – Bit Level Declaration: int x= 5 – int *ptr1 = &x; integers are of size 4bytes, which means: x: – Char c = ‘z’; char *ptr2 = &c; (‘z’ equals to 122) Char takes 1byte of memory: c: ptr1 ptr2 Decimal to binary conversion: ASCII table:

Pointers... MEMORY ADDRESS SPACE Address int x; int *foo; x= 123; foo = &x; foo x 0 foo contains the address it points at. *foo is the value that foo points at. &x is the address of variable x. &foo is the address of the pointer foo

Comparing Pointers int j = 5; int i = 5; int *ptrj1 = &j; int *ptrj2 = &j; int *ptri = &i; True/False: if (ptrj1 == ptrj2) ? if (ptrj1 == ptri) ? if (&ptrj1 == &ptrj2) ? if (*ptrj1 == *ptri) ? True False True

Assigning a value to a dereferenced pointer A pointer must have a value before you can dereference it (follow the pointer). int *x; *x=3; int foo; int *x; x = &foo; *x=3; ERROR! Overrode the value located in some address! this is fine x points to foo

Pointers to pointers int *x; int **y; double *z; x some int some *int some inty z some double

Pointers to pointers Example: – int i = 5; – int *p_i = &i; – int **pp_i = &p_i; Then: pp_i is memory location of … p_i *pp_i is memory location of … i **pp_i equals… 5

Pointers and Arrays Array name is basically a const pointer pointing at the beginning of the array. You can use the [] operator with pointers! Example: – int A[5]; – Creates a memory block of 5 integers on the stack (5x4bytes) where A (the pointer) points at the beginning of the array -> A[0]. (A = &A) A

Pointers and Arrays int *x; int a[5]={-1,-2,-3,-4,-5}; x = &a[2]; for (int i=0;i<3;i++) x[i]++; x is “the address of a[2] ” x[i] is the same as a[i+2] a x[0] x[1] x[2] x

Pointer arithmetic Integer math operations can be used with pointers: +, -, ++, --, +=, -= If you increment a pointer, it will be increased by the size of whatever it points to. Incrementing pointers will basically make it point to the “next” element in memory. int a[5]; a[0] a[1] a[2] a[3] a[4] int *ptr = a; *ptr *(ptr+2) *(ptr+4)

C++ char* char* is another way to represent strings in C++. (it actually came first - with C!) char* is an array of chars. char* arrays are terminated with ‘\0’ – “null terminated strings”. “denotes end of string”. char *msg= “RPI”; Length of string? 'R‘ msg null 'P‘'I‘\0 strlen(msg) == 3;

Using the Heap All primitives are stored in the stack, All that is made without new command is stored in the stack. ( except global variables and initailized char* – splab! ) Using the new keyword, we can now allocate memory on the heap. – int *i = new int; – string *str = new string(“hi there, heap is cozy!”); – int *arr = new int[5]; Deleting these objects can be done by using the delete keyword. – delete i; – delete str; – delete[] arr; Safe Delete: if (0 != p){ delete p; p=0; } DO NOT DELETE A PONTER NOT ALLOCATED BY NEW

Pointer Pitfalls Assigning values to uninitialized, null, or deleted pointers: int *p; int *p = NULL; int *p = new int; *p = 3;*p = 4; delete p; *p = 5; All of these cases end up with segmentation fault!

Dangling Pointer A pointer that points at nothing: Example: int *p, *q; p = new int; q = p; delete q; *p = 3; //illegal assignment! p and q point to the same location, q is deleted, results with p becoming a dangling pointer!

Memory Leaks Memory leak is when you remove the reference to the memory block, before deleting the block itself. Example: int *p = new int; p = NULL;//or a new other value p points at memory location of type int. p changed to point at null. Result? Must free memory block before changing reference. Memory leak!

A memory leak can diminish the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or devices stops working correctly, the application fails, or the system slows down. Use valgrind with –leak-check=yes option if your implementation has memory leaks.valgrind Valgrind User ManualValgrind User Manual, The Valgrind Quick Start Guide, Graphical User InterfacesThe Valgrind Quick Start GuideGraphical User Interfaces * This is why the –g flag is used when debugging!

DO NOT FORGET TO SUBMIT: – Homework0 – Homework1 – Homework2 The Targilonim help your exercise the things we learnt so far! READ COURSE ANNOUNCEMETNS! Presentations: Before You Leave!