INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Similar documents
DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Dynamic Memory Allocation

[0569] p 0318 garbage

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

Launchpad Lecture -10

CSC 1600 Memory Layout for Unix Processes"

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

Pointers, Dynamic Data, and Reference Types

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Homework #3 CS2255 Fall 2012

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

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

Object-Oriented Programming for Scientific Computing

Dynamic Allocation in C

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Pointers and Memory 1

Goals of this Lecture

CSC 211 Intermediate Programming. Arrays & Pointers

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

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

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Pointers and References

Section - Computer Science. int main() {! int a=10,b=20;! printf("a:%d B:%d\n",a,b);! a=(a+b)-(b=a);! printf("a:%d B:%d\n",a,b);!

Class Information ANNOUCEMENTS

Intermediate Programming, Spring 2017*

Variation of Pointers

CS 11 C track: lecture 5

CS61C : Machine Structures

EL2310 Scientific Programming

Computer Programming

Vector and Free Store (Vectors and Arrays)

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

CPSC 427: Object-Oriented Programming

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

CS201 Some Important Definitions

C++ for Java Programmers

Dynamic Allocation of Memory

Memory and C++ Pointers

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

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

Chapter 17 vector and Free Store. Bjarne Stroustrup

Vector and Free Store (Pointers and Memory Allocation)

Call The Project Dynamic-Memory

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

Variables, Memory and Pointers

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

Chapter 17 vector and Free Store

Short Notes of CS201

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

Chapter 17 vector and Free Store

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

Introduction to Programming Using Java (98-388)

CS201 - Introduction to Programming Glossary By

Programming Language Implementation

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Dynamic Allocation of Memory

CPSC 427: Object-Oriented Programming

1 Dynamic Memory continued: Memory Leaks

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

Dynamic Allocation in C

Assist. Prof. Dr. Caner ÖZCAN

Motivation was to facilitate development of systems software, especially OS development.

Dynamic memory allocation (malloc)

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

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

CSCI 171 Chapter Outlines

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

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

Run-time Environments - 3

Introduction to Computer Science Midterm 3 Fall, Points

C Structures & Dynamic Memory Management

Limitations of the stack

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

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


Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Pointers. Memory. void foo() { }//return

TI2725-C, C programming lab, course

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

C++ for Java Programmers

Motivation was to facilitate development of systems software, especially OS development.

Pointers and Dynamic Memory Allocation

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Lecture 8 Dynamic Memory Allocation

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.


CS110: PROGRAMMING LANGUAGE I

C++ Object-Oriented Programming

University of Kelaniya Sri Lanka

CS24 Week 2 Lecture 1

Chapter 1: Object-Oriented Programming Using C++

CSE 307: Principles of Programming Languages

C11: Garbage Collection and Constructors

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Memory (Stack and Heap)

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Transcription:

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria

INITIALISING POINTER VARIABLES Pointer variables are declared by putting an asterisk between data type and variable name: int *p; The contents of an uninitialised pointer are undefined Values:??? Initialise your pointers to 0 or NULL: int *p = 0; Address: 350 int *p // initialise a null pointer int *p = NULL; // same thing: NULL is a macro = 0 Values: 0 Address: 350 int *p

DYNAMIC VARIABLES Memory Stack Heap Static variables Memory allocated at compile time Maximum size must be known beforehand Dynamic variables Memory allocated at run time Use as much memory as you need, and return it back to the heap when done

OPERATOR NEW In C++, dynamic variables can be created using pointers and the operator new Operator new is used to allocate either a single variable, or an array of variables: new datatype; // single variable new datatype[size]; // an array of variables Variables allocated using new have no names, and must be assigned to a pointer variable: datatype *p = new datatype; int *p = new int; There is no direct access to the dynamically allocated memory you can only use it through pointer variables

OPERATOR NEW Consider: int *p; int x = 42; p = &x; And: int *p = new int; *p = 42; In both examples, pointer p points to a memory location that stores the value 42 In the first example, 42 is stored on the stack and can be accessed through x and *p In the second example, 42 is stored on the heap and can be accessed only through *p

OPERATOR DELETE All memory allocated using new must be manually de-allocated using delete The deallocated memory can be reused by allocating it to new variables Operator delete is used to deallocate both single variables and arrays of variables: int *ptrvar = new int; // allocate a single int delete ptrvar; // deallocate a single variable int *ptrarr = new int[x]; // allocate array delete [] ptrarr; // deallocate an array The delete operator does not delete the pointer it deletes (deallocates) the memory that the pointer points to

OPERATOR DELETE : DANGLING POINTERS The delete operator does not delete the pointer it deletes the memory that the pointer points to Before delete p; 500 42 Address: 350 500 After delete p; int * p 500??? Address: 350 500 int * p The heap memory is free, but p still stores an address

OPERATOR DELETE : DANGLING POINTERS A pointer that points to an address that is no longer valid is called a dangling pointer If you use a dangling pointer, you will either corrupt data on the heap, or your program will crash To avoid dangling pointers, explicitly set your pointers to NULL after you delete them: delete p; // deallocate heap memory p = 0; // set p to NULL NULL??? Address: 350 500 int *p

POINTERS & MEMORY LEAKS What happens if you don t delete pointers? void dosomething() { int *p = new int; *p = 42; } When you exit dosomething(), p goes out of scope However, the memory allocated to p remains allocated (reserved) it can not be reused by other variables Dynamically allocated memory can only be accessed through p When p goes out of scope, the memory is still allocated, but is inaccessible This is called a memory leak You will eventually run out of memory if you do this!

POINTERS & MEMORY LEAKS Loosing the address of dynamically allocated memory results in a memory leak: int x = 5; int *p = new int; // allocate memory p = &x; // old address lost, memory leak results Memory leak can also result from a double allocation: int *p = new int; // allocate memory p = new int; // allocate memory again // old address lost, memory leak results Make sure not to lose the addresses of dynamically allocated memory Provide a delete for every new

OPERATIONS ON POINTERS Assignment and relational operations are allowed on pointers: int *p, *q; // declare two pointers p = new int; *p = 3; q = p; // both q and p now point to // the same memory location Pointers can be compared: if(q == p) { // true if both q and p point to // the same memory location } else if(q!= p) { // true if q and p point to // different memory locations }

POINTER ARITHMETIC Integer addition and subtraction is allowed on pointers If p points to an integer, p + 1 is the address of the next integer in memory after p p - 1 is the address of the previous integer before p When calculating the result of a pointer arithmetic expression, the compiler always multiplies the integer operand by the size of the object being pointed to This is called scaling Eg., p++; increments the address stored in p by 4 bytes if p is an int pointer increments the address stored in p by 1 byte if p is a char pointer Pointer arithmetic is dangerous: if you don t know what you re doing, you might access memory of other variables, mess up the data, and make your program crash

QUESTION TIME Next lecture: Dynamic arrays Functions & pointers Shallow versus deep copy & pointers