SPL – Practical Session 2

Slides:



Advertisements
Similar presentations
SPL/2010 Pointers and Parameter Passing in C++ 1.
Advertisements

SPL – Practical Session 2 Topics: – Makefile – C++ Memory Management – Pointers.
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation Namespaces Simple Make Files (Ignore all class references.
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.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
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.
SPL Practical Session 1. Administrative Issues Reception Hour: TBD Course Site:
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Practice Session 3 Topics: References Objects - Classes Object construction Member Initialization List this, ->,. Operator= overloading Object Destruction.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
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.
SPL – Practical Session 2 Topics: – C++ Memory Management – Pointers.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
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.
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.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
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.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Yan Shi CS/SE2630 Lecture Notes
Memory Management.
Dynamic Allocation in C
CSC 533: Programming Languages Spring 2016
SPL Practical Session 1.
Object Lifetime and Pointers
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Computer Organization and Design Pointers, Arrays and Strings in C
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
CSC 533: Programming Languages Spring 2015
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Motivation and Overview
Objectives Identify the built-in data types in C++
Pointers Revisited What is variable address, name, value?
C Basics.
Pointers and references
Pointers.
Lecture 6 C++ Programming
Pointers and References
This pointer, Dynamic memory allocation, Constructors and Destructor
Pointers and References
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Built-In (a.k.a. Native) Types in C++
Memory Allocation CS 217.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers.
Pointers and References
Overloading functions
C++ Pointers and Strings
Homework Continue with K&R Chapter 5 Skipping sections for now
Pointers and References
C++ Pointers and Strings
Makefiles, GDB, Valgrind
Pointers, Dynamic Data, and Reference Types
Pointers and references
CSC 533: Programming Languages Spring 2019
SPL – PS1 Introduction to C++.
C Pointers Another ref:
SPL – PS2 C++ Memory Handling.
Presentation transcript:

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

Preprocessor: accepts source code( Preprocessor: accepts source code(*.cpp); removes comments; add the content of the include files. Compiler: translates source to assembly code (AND, OR, JMP, SUB etc.). Assembler: creates object code (machine code, 0-s and 1-s, *.o files). Linker: links the object files to an executable and creates an executable machine code; marks the main() as the starting point of the execution.

Example Program We have a program that contains 3 files: Run.cpp, HelloWorld.cpp, HelloWorld.h HelloWorld.h included in both .cpp files Executable should be the file helloWorld

Flags Needed for the Assignments -c: compile file. input: file.cpp, output: file.o. File is not executable! -o: parameter to specify name of output . -g: produces debugging information for debugger. -Wall: prints all errors/warnings in detail. -Weffc++: prints errors/warning that violate the guidelines in “Effective C++” and “More Effective C++” books. Read more: http://www.programmingforums.org/thread7219.html

How would you compile it?! helloWorld (executable binary) helloWorld.o run.o HelloWorld.cpp HelloWorld.h Run.cpp Compile Run.cpp without creating an executable: g++ -c –o run.o Run.cpp Compile HelloWorld.cpp without creating an executable: g++ -c -o helloWorld.o HelloWorld.cpp Linking the object files and creating an executable called helloWorld: g++ -o helloWorld run.o helloWorld.o

makefile the make utility

Why makefile? An advanced way to compile your program with a single line! After creating the makefile ofcourse… But that needs to be created only once! Saves a lot of time.. We’ll see how…

Makefile example code helloWorld: run.o helloWorld.o g++ –Wall –o helloWorld run.o helloWorld.o run.o: HelloWorld.h g++ –c Run.cpp helloWorld.o: HelloWorld.h g++ –c HelloWorld.cpp clean: rm –rf ./*.o helloWorld Compiling program: Command: make helloWorld Process: compiles first run.o compiles HelloWorld.o links run.o and helloWorld.o into helloWorld Removing binaries: make clean clean has no dependencies, so it runs the remove command.

How the Makefile Works T1: D1 D2 Commands To build T1, the make utility will work as follows: if either  D1 or D2 do not exist, build them (recursively). Check if both  D1 and D2 are up to date. If not, build them recursively. Check the date of  (the modification time). If  T1 is at least as new as BOTH  D1 and D2, we are done; Otherwise, follow the instructions given to build T1 

CC = g++ CFLAGS = -g -Wall -Weffc++ # All Targets all: hello # Executable "hello" depends on the files hello.o and run.o. hello: bin/hello.o bin/run.o @echo 'Building target: hello' @echo 'Invoking: C++ Linker' $(CC) -o bin/hello bin/hello.o bin/run.o @echo 'Finished building target: hello' @echo ' ' # Depends on the source and header files bin/hello.o: src/HelloWorld.cpp include/HelloWorld.h $(CC) $(CFLAGS) -c -Linclude -o bin/hello.o src/HelloWorld.cpp bin/run.o: src/Run.cpp include/HelloWorld.h $(CC) $(CFLAGS) -c –Linclude -o bin/run.o src/Run.cpp #Clean the build directory clean: rm -rf bin/* Example from Practical Session 2 Part B – Makefile Segment Reading material: http://dev-faqs.blogspot.com/2011/03/simple-makefile-tutorial.html

When you type "make" in your shell, the script will look for a file "makefile" in the same directory and will execute it. By default, make will only execute the first target in the makefile; so, make sure the first target will cause a complete build. Important - the space you see to the left of some lines are tabs, and not space characters. makefile variables are all upper-case, and are referenced using ${VAR_NAME}.

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: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

Primitives and Arrays pi = &j; pi[3] = 5; pi = A; pi[3] = 5; pi++;   pi = A; pi[3] = 5;  pi++;   pi[0] = 1; // int A[10]; int s=0;  int *pi; int j;

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 264 bytes! Each memory cell is 1 byte. (byte-accessible machines – most machines today) Each pointer takes a static size of 4 bytes in a 32bit OS, 8bytes in a 64bit OS. Pointers themselves are saved on the stack.

Java vs. C++ Java’s References C++ Pointers 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" Have access to actual memory locations. Can point to anything! The null value in C++ is the number 0 (memory address 0). In c++11, nullptr is used to denote a null pointer.

Pointers – Bit Level Declaration: int x= 5 x: c: 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 1 1 Decimal to binary conversion: http://www.wikihow.com/Convert-from-Decimal-to-Binary ASCII table: http://www.asciitable.com/ ptr2

Pointers int x; int *foo; x= 123; foo = &x; 1 2 3 MEMORY ADDRESS SPACE ... MEMORY ADDRESS SPACE 1000 1001 1002 1003 1004 1005 1006 81345 81346 81347 Address int x; int *foo; x= 123; foo = &x; x 1 2 3 foo 1000 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 *ptri = &i;   True/False: if (ptrj1 == ptrj2)  ? if (ptrj1 == ptri)  ? if (&ptrj1 == &ptrj2)  ? if (*ptrj1 == *ptri) ?  True False 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; x does not point to anything! ERROR! this is fine x points to foo

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

Pointers to pointers Example: Then: 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

Pointers and Arrays a x x[0] x[1] x[2] 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] ” a x[i] is the same as a[i+2] x -1 -2 -3 -4 -5 x[0] x[1] x[2]

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 *ptr = a; *(ptr+2) *(ptr+4) *ptr a[0] a[1] a[2] a[3] a[4] int a[5];

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? strlen(msg) == 3; msg null 'R‘ 'P‘ 'I‘ \0

Using the Heap All primitives are stored in the stack, char* var = “ “; var is also stored in the stack. All that is made without new command are stored in the stack. 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 (nullptr != p){ delete p; p=nullptr; } 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 = nullptr;//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 User Manual, The Valgrind Quick Start Guide, Graphical User Interfaces * This is why the –g flag is used when debugging!

lvalue, rvalue rvalue cannot be on left side of an expression. int main(int argc, char** argv) {   int i = 5;    int j = 4;    char *s = "test";    j = 5 * 22;    i = i + j;  } int i = 5; // i is lvalue, 5 is rvalue   int j = 4; // j is lvalue, 4 is rvalue   char *s = "test"; // s is lvalue, "test" is rvalue   j = 5 * 22; // j is lvalue, 5 * 22 is rvalue   i = i + j; // i is lvalue, i + j is rvalue

References (lvalue references) A variable that is used to refer to another variable (alias). Notation: varType &refVar = objVar; Example: int i =3; int &r =i; r = 4; //will change the value of i to 4

Hides indirection from programmer Must be typed (int, double…) Can only refer to the type to which it can point. Checked by compiler int &r = i; // can only refer to int Must always refer to something Must be initialized upon creation. Cannot be initialized to 0 or NULL. Value cannot be changed once initialized.

What are they for? When you send a variable to a function: Function: void removeLast(intArray intArr){ ... }; intArray myArr = intArray(1,2,3,4,5); removeLast(myArr); Variable is passed by value! Which means a copy of myArra is created and sent to the function. Problem? Functions that alter the values of the variable sent to them cannot alter the variable! They will alter a copy of the variable.

myArr = removeLast(myArr); Possible solution? Alter the function to return the same object type: intArray removeLast(intArray intArr){ … }; Usage: myArr = removeLast(myArr); Another solution? References! void removeLast(intArray& intArr){ … }; removeLast(myArr); Common places references are used at? Used in copy constructor Used in operator overloading

Lvalue Reference vs. Pointers Referencing is done directly. User interacts with it as if it was the object itself. Must be typed. Must be initialized upon creation. Can’t be altered after. Pointer: Stores the memory address of the object. Requires dereferencing in order to retrieve the object. Does not have to be typed. (use casting..) Does not have to be initialized upon creation. Can be altered afterwards. Dereferencing: the act of getting what the pointer is pointing at.