CS 222: Pointers and Manual Memory Management

Similar documents
CSC 1600 Memory Layout for Unix Processes"

Dynamic Data Structures. CSCI 112: Programming in C

Pointers, Dynamic Data, and Reference Types

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

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

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

CS24 Week 2 Lecture 1

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Heap Arrays. Steven R. Bagley

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

Dynamic memory allocation (malloc)

Intermediate Programming, Spring 2017*

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CS 222: Arrays, Strings, Structs

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CS 11 C track: lecture 5

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

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

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

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

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CS 61c: Great Ideas in Computer Architecture

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

First of all, it is a variable, just like other variables you studied

Fall 2018 Discussion 2: September 3, 2018

COP 3223 Final Review

Heap Arrays and Linked Lists. Steven R. Bagley

CS61C : Machine Structures

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

CS 2461: Computer Architecture I

Arrays and Memory Management

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

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

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Lecture 8 Dynamic Memory Allocation

Understanding Pointers

CS107, Lecture 9 C Generics Function Pointers

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

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

C Characters and Strings

Introduction to C: Pointers

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Quick review pointer basics (KR ch )

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

Arrays and Pointers in C. Alan L. Cox

CS61C : Machine Structures

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

CS201- Introduction to Programming Current Quizzes

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

POINTER AND ARRAY SUNU WIBIRAMA

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

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

Arrays and Pointers (part 1)

Dynamic Allocation in C

ME964 High Performance Computing for Engineering Applications

Memory, Arrays & Pointers

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Dynamic memory. EECS 211 Winter 2019

CS 241 Data Organization Binary Trees

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

C Structures & Dynamic Memory Management

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

COP 3223 Final Review

ARRAYS(II Unit Part II)

How about them A s!! Go Oaktown!! CS61C - Machine Structures. Lecture 4 C Structures Memory Management Dan Garcia.

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

Memory Management. CSC215 Lecture

Dynamic Allocation in C

Kurt Schmidt. October 30, 2018

CS61, Fall 2012 Section 2 Notes

Welcome! COMP s1. Programming Fundamentals

CS61C : Machine Structures

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows


C-LANGUAGE CURRICULAM

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Arrays and Pointers (part 1)

Structures and Pointers

Dynamic Memory & ADTs in C. The heap. Readings: CP:AMA 17.1, 17.2, 17.3, The primary goal of this section is to be able to use dynamic memory.

Dynamic Memory & ADTs in C

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Fast Introduction to Object Oriented Programming and C++

Common Misunderstandings from Exam 1 Material

High Performance Programming Programming in C part 1

CS201 Some Important Definitions

Intermediate Programming, Spring 2017*

Transcription:

CS 222: Pointers and Manual Memory Management Chris Kauffman Week 4-1

Logistics Reading Ch 8 (pointers) Review 6-7 as well Exam 1 Back Today Get it in class or during office hours later HW 3 due tonight Any questions? HW 4 up tomorrow, Due next week More advanced struct, arrays Multidimensional arrays

Goals Exam 1 Feedback String Practice Pointers

Exam 1 Stats Range Count 90-100 12 80-89 16 70-79 3 60-69 3 50-59 4 40-49 1 Stat Val R2014 Count 39 33 Min 45.00 43.64 Max 98.33 100.00 Range 53.33 56.34 Average 81.84 80.67 Median 86.67 83.64 StdDev 13.48 16.33

Strings as Input scanf can read strings with %s { } Must have a character array of sufficient size Don t use & char buffer[1024]; scanf("%s",buf); Q: How would determine if the string read is the string Millenium?

Oh, the bits you ll smash scantest.c: Let s make some trouble http://stackoverflow.com/questions/1345670/ stack-smashing-detected

Practice Program wordguess.c A mystery word called answer Repeated prompting to user for guess word Check if guess word is correct End game is guess is correct Otherwise, reveal progressive characters of answer Write this program for me Required Elements Read a string using scanf() strcmp() is very useful if(strcmp(answer, guess) == 0) /* is it the right word? Loop, tracks number guesses Print single characters with printf()

Other Cool Functions in string.h See stringlib.c Length : strlen() myint length(str) int l = strlen(str); Copy : strcpy() str1 str2 strcpy(str1, str2); Concatenation : strcat() str1 str1 str2 strcat(str1, str2);

A few Character Functions In ctype.h: can be useful for checking conditions int isupper(char c); int islower(char c); int isspace(char c);... int toupper(int c); int tolower(int c);... Not really needed for HW: just check specifically for characters with ==.

Relation of *a and a[] What is a versus what is c? int a[10]; char c[5]; A memory address Access a[4] means a + 4*sizeof(int) Access c[4] means c + 4*sizeof(char) Second half explicitly deal with memory locations int *ap; a pointer to memory which contains ints char *cp; a pointer to memory which contains chars

One common error: Passing array args Some function on arrays double arrfunc(int [] arr, int length); double otherfunc(int arr[], int length); Call function with an array int ia[5] = {2, 2, 0, 3, 0}; double ans = arrfunc(ia, 5); Call with bare name only No square braces WRONG: arrfunc(ia[], 5); No size indication in square braces WRONG: arrfunc(ia[5], 5);

Arrays are a Fixed Memory Address What are a and c? int a[10]; char c[5]; A memory address Access a[4] means a + 4*sizeof(int) Access c[4] means c + 4*sizeof(char) More on sizeof after the break

Pointers A memory address A fundamental type in C, like int,char,double Point at a data type like int,char,double Can also be a void pointer - generic pointer Very unfortunate homonyms void fun(void); takes no args, returns nothing void pointer can actually point at stuff NULL pointer points at nothing Null character \0 ends strings Question: Pointers are a data type. What should we discuss next?

Pointer Basics Define Done for you Declare Use a * in front of another type int *intptr; // I point at ints double *doubs; // I point at doubles char *chars; // I point at chars ze_struct *zs; // Well, you get the point Access x = intptr; What type should x have? Assign intptr = x; Wait a minute.... what aren t you telling me?

The Interesting Operations & : Address Operator Applicable to any variable Produces memory address of the variable Results in a pointer int i = 2; int *ptr = &i; // Point at i int j = 3; ptr = &j; // Point at j LHS must be a pointer RHS should be some variable * : Dereference Operator Applicable to pointers Produce contents of pointer Results in pointed at type *ptr on RHS: access value pointed at variable i int i = 2; int *ptr = &i; int j = *ptr; *ptr on LHS: allows assignment to pointed at variable i *ptr = 10; if(i == 10){ printf("wow!"); } See simplepointers.c

* and & are Inverse Operations f () and g() are inverse operations if x = f (g(x)) = g(f (x)) f (x) = x + 1 and g(x) = x 1 are inverse functions Derivative and Integral are inverse operations f Deriv(Integ(f )) Integ(Deriv(f )) *var and &var are inverse operations var == *(&var) var == &(*var) For this to work, what type must var have?

The Pointer Play Hot seat thespians act out the drama of C Script in pointerplay.c

First Real Uses Pointers as function arguments are interesting nonlocal_set.c Remember how we can t return more than one thing from a function? Now you can: multiplereturns.c

Exercise Write a function that swaps two integers swap_ints takes two integer pointers What does its prototype look like? How is the swap accomplished?

Relation of *ap and a[] What are a and c? int a[10]; char c[5]; A memory address Square brace syntax is offset from that location Access a[4] means a + 4*sizeof(int) Access c[4] means c + 4*sizeof(char) How about for pointers? int *ap; char *cp; Also a memory address Pointers also allow [] syntax Access ap[4] means a + 4*sizeof(int) Access cp[4] means c + 4*sizeof(char) See arrayvptr.c

Differences of *ap and a[] Array a[] A fixed memory location (stack or global memory) Can t move the array around Can change elements of the array: a[1] = x; Usually points at more than one thing Pointer *ap Only points at something else Can change where ap points: ap = &x; change data at location: *ap = x; change data at offset: ap[1] = x; May point at 1 thing or a whole array of things Must use context to tell...

Remember Memory Layout Stuff we ve had so far is on the stack What about that other part?

Stack and Heap Stack Grows when functions get called, shrinks when functions finish Compiler knows how much to shrink and grow stack For this function I need 2 ints and an array of 10 doubles 2*4 + 10*8 = 88 bytes Stack space is there for you automatically Heap For memory with size not known at compile time Used for run-time allocation Read n from the user Allocate space for n integers Programmer (you) must manually manage heap space With help from libraries

malloc and free malloc(n) Allocate n bytes somewhere on the heap used as void *p = malloc(n); p now points at memory on heap which can be used Allocation may fail - not enough memory free(p) Deallocate memory pointed to by p Memory available for further calls from malloc Gives errors if p doesn t point to malloc d memory

Allocating Useful Stuff Prototype: void *malloc(size_t size); size_t is an integer-like value (probably long, 64-bit integer) Usually want int *, double *, planet_t *, not void * Need to figure out how many bytes required Use two C features for this: sizeof and casting

Casting Force conversion of one type to another Numerical int i = (int) 45.3 * 0.4432; Pointer char *str = (char *) malloc(100); Pointer planet_t *p = (planet_t *) malloc(100); Gross double d = (double) H ; Old School int ip = (int) &i; Bad Bad double q = (double) str; Compiler, I m removing the safety net because it s in the way.

sizeof() Like a function that returns number of bytes for a type sizeof(int) is # bytes an integer uses sizeof(planet_t) is # bytes an planet_t uses sizeof.c

malloc useful stuff See malloc.c chars/string char *str = (char *) malloc(sizeof(char)*100); doubles double *arr = (double *) malloc(sizeof(double)*100); planet_t planet_t *p = (planet_t *) malloc(sizeof(planet_t)*100);

Fun things to try See how much memory you can get: malloc_madness.c

free Keep using malloc and eventually it wil fail: no memory left Use free to deallocate Important for long-running programs Memory leak: malloc, lose pointer, can t free, program gets bloated