Pointers, Heap Memory Rudra Dutta CSC 230 - Spring 2007, Section 001.

Slides:



Advertisements
Similar presentations
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Chapter 10.
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.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Introduction to C Programming
Pointers Applications
Basic Input/Output and Variables Ethan Cerami New York
String Escape Sequences
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Storage & Linkage: Effects on Scope Rudra Dutta CSC Spring 2007, Section 001.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
CHAPTER 8 CHARACTER AND STRINGS
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
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.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CSE 220 – C Programming malloc, calloc, realloc.
Computer Organization and Design Pointers, Arrays and Strings in C
© 2016 Pearson Education, Ltd. All rights reserved.
Chapter 2 - Introduction to C Programming
Revision Lecture
Chapter 18 I/O in C.
Chapter 2 - Introduction to C Programming
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Chapter 2 - Introduction to C Programming
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chapter 2 - Introduction to C Programming
Chapter 2: Introduction to C++.
Chapter 2 - Introduction to C Programming
Programming Languages and Paradigms
Introduction to C Programming
Presentation transcript:

Pointers, Heap Memory Rudra Dutta CSC Spring 2007, Section 001

Copyright Rudra Dutta, NCSU, Spring, Main Ideas Location, Address – Variables all have to be stored some“where” Address is a number – Can be stored as a value – Can be manipulated Can be used to implement call by reference Re-visit some issues with this view – printf, scanf – Arrays – Strings

Copyright Rudra Dutta, NCSU, Spring, Location of a Variable Address or location of a variable is a number – That number can be said to “point” to the variable – Address can itself be stored in a pointer variable – True whether memory is in heap or stack int i; something(int m) { float k; } main () { int i; for (i=0; i<3; i++) { something (i); }

Copyright Rudra Dutta, NCSU, Spring, Address Values C allows extracting address of any variable – Use operator & – Returns a value of type pointer – “Indirection” or “referencing” main () { int i; for (i=0; i<3; i++) { printf (“%x\n”, & i); }

Copyright Rudra Dutta, NCSU, Spring, Natural Questions What are typical value of an address for a variable on the stack, on the heap, global? – Programmer is not supposed to ask How large are the values? – Platform dependent – Must be reasonably large, since process virtual memory can be quite large – Can print out using %x or similar What about multi-byte variables? – Address points to first byte of storage

Copyright Rudra Dutta, NCSU, Spring, Pointer Variables Variables to store addresses of other variables – Typed to match variable pointed to – Can be “de-referenced” to access original variable Dereferencing operator - * – Unfortunately, same as multiplication Different precedence (see table on website) – Moreover, also used to define pointer variables int i; something(int *pm) { int *p_local; p_local = pm; *p_local = 25; } main () { int i; for (i=0; i<3; i++) { something (&i); } Dereferencing creates lvalue

Copyright Rudra Dutta, NCSU, Spring, Pointer Types Two possible views: – A pointer points to a particular variable, which has a type and hence a number of bytes required to keep it. So the pointer must be linked to that type. Or, “how would you know how to dereference?” – A pointer is a pointer is a pointer - it is a variable which holds the address of a particular byte (starting byte). Since the address of any byte is the same, all pointers require the same amount space to store, so there should just be one generic pointer type. Or, “how do you know what kind of pointer you have?” Both views represented in standard – Fundamentally first view (typed) – But generic pointers defined in ANSI standard (later)

Copyright Rudra Dutta, NCSU, Spring, Call By Reference The first does not work, the second does swap(int a, int b) { int temp; temp = a; a = b; b = temp; return; } swap(int *pa, int *pb) { int temp; temp = *pa; *pa = *pb; *pb = temp; return; }

Copyright Rudra Dutta, NCSU, Spring, Basic Pointer Access Examples Define a character variable c and two pointers p and q to point to it Point p to point to c Use p to write ‘a’ into c Point q to c using p Read out c using q What are the value of : – (*p == *q) – (p == q) – (&p == &q)

Copyright Rudra Dutta, NCSU, Spring, Pointer Definition Pitfall Pointer “types” are not really types – Definition parsed as starting with fundamental type – Need to be careful about multiple definitions on a line int *p; int *q; int* p; int* q; int *p, *q; int* p, q; An integer pointer p, an integer q

Copyright Rudra Dutta, NCSU, Spring, Address Arithmetic Address values are just numbers – Can be operated on (added, subtracted) Pointer variables just store addresses – Can be incremented, decremented Integers added or subtracted to pointer give: – Pointer values pointing to objects after or before – Incrementing a pointer points to the next object NOT next byte Pointer values subtracted from pointer values: – Number of objects between one and the other NOT number of bytes What is the meaning of such operations?

Copyright Rudra Dutta, NCSU, Spring, Address Arithmetic - Examples What makes sense? – Pointer value +/- integer value – Pointer value - pointer value What does not? – Pointer value + pointer value p int i; int *p; int *q; p = &i; printf (“%x\n”, p); p++; printf (“%x\n”, p); q = p + 3; printf (“%d\n”, q-p); pq int takes 2 bytes in example

Copyright Rudra Dutta, NCSU, Spring, Arrays Revisited Why would pointer arithmetic be useful? – One answer : arrays – (The other answer: heap memory - later) Defining an array always creates contiguous storage for the various array elements – Successive elements can be accessed by pointer increment In fact, there are no real arrays in C – An array definition creates memory and a pointer to the first element – This pointer is the “name” of the array

Copyright Rudra Dutta, NCSU, Spring, Pointer Access to “Arrays” Name of array is pointer to first element – Type of that pointer is pointer to element type Consider the definition int ia[30]; – ia is (just like) a variable of type int* The first element can be accessed as – ia[0] – *ia The second element can be accessed as – ia[1] – *(ia+1) In fact, there is no difference between the two – Compiler internally translates to pointer (address) access

Copyright Rudra Dutta, NCSU, Spring, Arrays are really Pointers int main () { int p[5], i; for (i=0; i<5; i++) { p[i] = i*i; } for (i=0; i<5; i++) { printf ("%d ", p[i]); } printf ("\n"); }

Copyright Rudra Dutta, NCSU, Spring, Arrays are really Pointers int main () { int p[5], i; for (i=0; i<5; i++) { p[i] = i*i; } for (i=0; i<5; i++) { printf ("%d ", *(p+i)); } printf ("\n"); }

Copyright Rudra Dutta, NCSU, Spring, Arrays are really Pointers int main () { int p[5], i; for (i=0; i<5; i++) { p[i] = i*i; } for (i=0; i<5; i++) { printf ("%d ", i[p]); } printf ("\n"); }

Copyright Rudra Dutta, NCSU, Spring, Arrays are really Pointers int main () { int p[5], i; for (i=0; i<5; i++) { p[i] = i*i; } printf ("%d ", 0[p]); printf ("%d ", 1[p]); printf ("%d ", 2[p]); printf ("%d ", 3[p]); printf ("%d ", 4[p]); printf ("\n"); }

Copyright Rudra Dutta, NCSU, Spring, Essential Difference in Definition How do the effects of these two differ? – int *p; – int p[5]; How do the effects of these two differ? – int p[] = {0, 1, 2, 3, 4}; – int p[5] = {0, 1, 2, 3, 4}; How do the effects of these two differ? – int p[]; – int p[5]; How do the effects of these two differ? – int *p; p = &i; – int p[5]; p = &i;

Copyright Rudra Dutta, NCSU, Spring, Array Access to Pointers It works the other way too Write code to print out the 5 integers in p – int p[5]; Simplify: – &p[3] – *&p[3] – *(p+(&p[5]-(p+3)))

Copyright Rudra Dutta, NCSU, Spring, Pointer Problems “Dangling” pointers – Pointers that do not point to anything in particular – Value stored in the pointer variable is “garbage” – May point to areas not accessible to programmer Dereferencing will cause program crash (even reading) – May point to somewhere inside process memory Dereferencing can cause unforeseen results

Copyright Rudra Dutta, NCSU, Spring, Dangling Pointers How do we get dangling pointers? – A pointer is dangling as soon as it is defined – Pointer with a broader scope (e.g. global) int main () { int *p, i; p = &i; printf (”%d\n", *p); } int *p; int something () { int i; p = &i; printf (”%d\n", *p); }

Copyright Rudra Dutta, NCSU, Spring, Strings Revisited There are no real strings in C – Strings are just shorthand for char arrays Special conventions: – Entire array can be literally quoted by the use of “” – End of “string” is indicated by a 0 value In character format, literally quoted as ‘\0’ - escape character Problematic question: where are literally quoted arrays located? – Literally quoted numbers are not any“where” but ephemeral values – Literal arrays must be in some memory - but treat as read-only (more later) h e l l o \0

Copyright Rudra Dutta, NCSU, Spring, String Example What happens? int main () { char str[10] = "hello"; int i; printf ("%s\n", str); for (i=0; i<10; i++) { printf ("%c ", str[i]); } Change array initialization to form not using special “string” convention - ?

Copyright Rudra Dutta, NCSU, Spring, String Example int main () { char str[10] = {'h','e','l','l','o','\0','1','2','3','4'}; int i; printf ("%s\n", str); for (i=0; i<10; i++) { printf ("%c ", str[i]); } str[0] = ‘c’; printf ("%s\n", str); } What happens if you supply too few literals ? – Rest initialized to zero

Copyright Rudra Dutta, NCSU, Spring, Character Type Functions It is easy to check whether a particular character is lowercase, numeric, etc.,… – Provided you know what the character set is (ANSI?) Standard library provides portable methods to check character types – Functions declared in ctype.h int isalnum(int c) is c an alphanumeric int isalpha(int c) is c an alphabetic letter int islower(int c) is c a lower case letter int isupper(int c) is c an upper case letter int isdigit(int c) is c a digit int isxdigit(int c) is c a hexadecimal digit int isodigit(int c) is c an octal digit

Copyright Rudra Dutta, NCSU, Spring, Character Type Functions int isprint(int c) is c printable (not a control character) int isgraph(int c) is c printable (not a space) int ispunct(int c) is c printable (not space or alphanumeric) int isspace(int c) is c whitespace int tolower(int c) return lowercase version of c int toupper(int c) return uppercase version of c

Copyright Rudra Dutta, NCSU, Spring, Example Given a pointer s to a string and an integer number n, return 0 if the string terminates in n -1 characters or less (that is any of the first n characters pointed to by s are ’ \0 ’ ), 1 if not. Examples: "platform" "platform" 9 - 0

Copyright Rudra Dutta, NCSU, Spring, Formatted I/O Revisited Formatted printing - print the variables supplied as arguments (and literal text) – printf (“The %d-th entry is %f\n”, i, p[i]); – The 3-th entry is BUT, number of arguments is variable – (C provides specific syntax - later) – How does such a function know how many arguments, of what type? – Consider what happens to the stack Answer: first argument (must be present) must somehow communicate – Format string in printf performs this function

Copyright Rudra Dutta, NCSU, Spring, Formatted Input Provided as library function scanf – Two aspects of stack memory Use of format string just as in printf – First argument tells function the number of arguments that follow However, the job of scanf is to “read in” values – Logically, “Read in a decimal integer and store into the integer variable i” – Call by value does not allow modifying argument – Need to pass pointer - “call by reference” scanf (“%d”, &i);

Copyright Rudra Dutta, NCSU, Spring, Quick Examples Write scanf statements to: – Read in three decimal integer values into i, j, k – Read in a decimal integer into i, and a character into c – Read in a character into c, and a decimal integer into i – Read in two long integers separated by the text “ and ” into l1, l2

Copyright Rudra Dutta, NCSU, Spring, Two Uses of Format Each % in the format string indicates one formatting command, also implies a variable A %d in the format string: – Tells printf to print 4 as 4, not or 4e0 – Tells scanf to stop reading when next character cannot be part of a printed decimal integer 44 is read as 44, 4 4 is read as 4 (next one left in stream) BUT also: – Tells printf to read the next argument from the stack to supply the value to print, and interpret as int – Tells scanf to write sizeof(int) bytes into the place pointed to by the next pointer, in int representation

Copyright Rudra Dutta, NCSU, Spring, Distinctions Whitespace – printf - whitespace in format string is just something literal to be printed to the output stream Objective is human readability – scanf - whitespace in input stream is something that indicates break between variables Whitespace in format string means “skip over literally” What about newline and tab? Conversions - mostly similar, but – scanf needs qualifiers for short, long, etc. What to store the value read in as – printf does not need - can provide to format output Knows from variable storage, and cannot be overridden

Copyright Rudra Dutta, NCSU, Spring, String I/O Remember - – String is just a char array, with null termination convention – Array is just contiguous variables, with array name pointer to first element printf has a special treatment for strings – With %s conversion, expects pointer to char – Also expects (prints until) null termination scanf has no special treatment (but seems to!) – Expects pointer, as always But now string name can be passed, no indirection – Also writes null termination after characters – Expects enough memory to write the whole string

Copyright Rudra Dutta, NCSU, Spring, Heap Memory General store of free memory – Programmer may request chunks of bytes, must manage use Memory is allocated from system – Allocation cannot be a language feature – Functionality made available through library Paired with facility to de-allocate - return memory to allocator Two widely used functions - malloc and free – Also calloc Important - cannot assume any ordering between chunks

Copyright Rudra Dutta, NCSU, Spring, General Use Use malloc or calloc to obtain chunks of free memory – Call may fail, check pointer value returned – calloc initializes to zero, malloc does not initialize – calloc takes two arguments – In general, best to use sizeof to specify size When use completed, use free to return chunk – Use free only with pointer values returned by malloc or calloc – Do not free from middle of an allocated block – Freeing creates dangling pointer Set to NULL after free - NOT automatic!

Copyright Rudra Dutta, NCSU, Spring, Examples p = malloc (2 * sizeof (int)); *p = 24; *(p+1) = *p+1; free (p); p = NULL; p = malloc (sizeof (int)); *p = 24; q = malloc (sizeof (int)); q = p; (*q)++; free (q); *p = 25; free (p); *p++ = (*p)++;

Copyright Rudra Dutta, NCSU, Spring, The void Type A type which is “nothing” – Storage-wise - nothing to store, so no bytes Functions may return void type – Retains function call discipline, but allows saying “this function does not return anything” – Equivalently, “the return value of this function occupies zero bytes on the stack” However, primary motivation comes from pointers and malloc A pointer is a pointer is a pointer - it is a variable which holds the address of a particular byte – Previously encountered question: how do you know what type of pointer you have?

Copyright Rudra Dutta, NCSU, Spring, Pointer Types Clearly, types of pointer variables (like all other variables) obtained from definition – Difference - does not affect amount of storage required for that variable itself, or interpretation of bytes Affects interpretation of location pointed to Better question: Can you know, just from the value of a pointer variable, what type it is pointing to? – Answer: No – Opens up possibility of interpreting one pointer type as another – NOT a pathological case - standard programming tool/trick How to convert? – Explicit casting, as usual – int *p; char *q; – q = (char *) p;

Copyright Rudra Dutta, NCSU, Spring, Generic Pointers Related question: What type of pointer should a function like malloc return? – Programmer’s purpose will differ on different calls – Used to be int *, programmer needed to cast each time Solution: define a “generic pointer” – Identifies a byte location in memory, but says nothing about how many bytes from there are being pointed to Size of “object being pointed to” is zero – Pointer to nothing - a void * pointer malloc etc. can and should return such pointers char *int *void *

Copyright Rudra Dutta, NCSU, Spring, The void * Type Specific rules with respect to void pointers Points to “nothing”, which implies – Such a pointer can never be de-referenced – Compiler does not know how many bytes to pull out, nor how to interpret More correctly, knows that number of bytes is zero Must make malloc simpler – Must not require casting of return type every time – Special rule: void * can be silently cast into other pointer types – Irony: programmer is never sure of portability, so ends up casting anyway

Copyright Rudra Dutta, NCSU, Spring, Read: Pointers – Chapter 5 – Sections later printf, scanf – Chapter 7 – Sections 7.3, later malloc etc. – man pages – Sections 7.8.5, optionally 8.7