review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with little protection

Similar documents
Reference slides! C Strings! A string in C is just an array of characters.!!!char string[] = "abc";! How do you tell how long a string is?!

review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with little protection

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)!

CS61C : Machine Structures

Review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with little protection

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

CS61C : Machine Structures

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

CS61C : Machine Structures

CS61C : Machine Structures

Lectures 13 & 14. memory management

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

Has there been an update to ANSI C? Lecture #3 C Pointers Yes! It s called the C99 or C9x std

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

CS61C : Machine Structures

CS61C : Machine Structures

ECE 15B COMPUTER ORGANIZATION

CS61C : Machine Structures

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

More C Pointer Dangers

HW1 due Monday by 9:30am Assignment online, submission details to come

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

CS61C : Machine Structures

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

Introduction to Computer Architecture

Agenda. Pointer Arithmetic. Pointer Arithmetic pointer + number, pointer number 6/23/2011. Pointer Arithmetic: Peer Instruction Question

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

CS 61c: Great Ideas in Computer Architecture

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists

CS61C : Machine Structures

Number review... Lecture 3 Introduction to the C Programming Language (pt 1) Has there been an update to ANSI C?

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

C Arrays, Strings, More Pointers Instructor: Steven Ho

Numbers: positional notation. CS61C Machine Structures. Faux Midterm Review Jaein Jeong Cheng Tien Ee. www-inst.eecs.berkeley.

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

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

Intro to C: Pointers and Arrays

Functions:"" Breaking"large"computing"tasks"to" smaller"ones"

Intermediate Programming, Spring 2017*

Review! Lecture 5 C Memory Management !

CS 11 C track: lecture 5

CS61C : Machine Structures

CSC 1600 Memory Layout for Unix Processes"

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

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

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

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

CS61C : Machine Structures

Lecture 7: Procedures and Program Execution Preview

CS61C : Machine Structures

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

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

CS61C : Machine Structures

CS24 Week 2 Lecture 1

Heap Arrays and Linked Lists. Steven R. Bagley

ME964 High Performance Computing for Engineering Applications

CSC C69: OPERATING SYSTEMS

Processes. Johan Montelius KTH

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

A process. the stack

CMSC 341 Lecture 2 Dynamic Memory and Pointers

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

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

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Heap Arrays. Steven R. Bagley

IT 252 Computer Organization and Architecture Introduction to the C Programming Language

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

CS61C : Machine Structures

Programming in C - Part 2

Pointers, Arrays, Memory: AKA the cause of those Segfaults

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

Lecture 2: C Programm

CS61C : Machine Structures

Dynamic Data Structures. CSCI 112: Programming in C

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

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

CS61C : Machine Structures

Data Representation and Storage. Some definitions (in C)

Understanding Pointers

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

Pointers in C/C++ 1 Memory Addresses 2

Arrays and Memory Management

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

CS61C : Machine Structures

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

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


Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output

Kurt Schmidt. October 30, 2018

Introduction to C: Pointers

REFERENCES, POINTERS AND STRUCTS

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Advanced Systems Programming

Character Strings. String-copy Example

Lecture 10: Program Development versus Execution Environment

EL2310 Scientific Programming

QUIZ. What are 3 differences between C and C++ const variables?

Transcription:

CS61C L05 Introduction to C (pt 3) (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 Introduction to C (pt 3) C Memory Management 2008-02-01 Lecturer SOE Dan Garcia Hello to Scott Sloan from Superior, WI! www.cs.berkeley.edu/~ddgarcia Sci-Fi Realities the predictions of the Sci-Fi analysts feel will become reality and when: Biometric Security voice, iris, retinal scans [2010], Space Tourism [2013], Holodeck [2016], Self-Aware Computers [2019], Domestic Robots [2020]. Get in line! www.pcworld.com/article/id,141682-page,1-c,desktoppcs/article.html Review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with little protection Array bounds not checked Variables not automatically initialized (Beware) The cost of efficiency is more overhead for the programmer. C gives you a lot of extra rope but be careful not to hang yourself with it! CS61C L05 Introduction to C (pt 3) (2) Pointers (1/4) review Pointers (2/4) review Sometimes you want to have a procedure increment a variable What gets printed Solved by passing in a pointer to our subroutine. Now what gets printed void AddOne(int x) x = x + 1; y = 5 void AddOne(int *p) *p = *p + 1; y = 6 int y = 5; AddOne( y); printf( y = %d\n, y); int y = 5; AddOne(&y); printf( y = %d\n, y); CS61C L05 Introduction to C (pt 3) (3) CS61C L05 Introduction to C (pt 3) (4) Pointers (3/4) Pointers (4/4) But what if what you want changed is a pointer What gets printed Solution! Pass a pointer to a pointer, declared as **h Now what gets printed void IncrementPtr(int *p) p = p + 1; *q = 50 A q void IncrementPtr(int **h) *h = *h + 1; *q = 60 A q q int A[3] = 50, 60, 70; int *q = A; IncrementPtr( q); printf( *q = %d\n, *q); 50 60 70 int A[3] = 50, 60, 70; int *q = A; IncrementPtr(&q); printf( *q = %d\n, *q); 50 60 70 CS61C L05 Introduction to C (pt 3) (5) CS61C L05 Introduction to C (pt 3) (6)

CS61C L05 Introduction to C (pt 3) (7) Dynamic Memory Allocation (1/4) C has operator sizeof() which gives size in bytes (of type or variable) Assume size of objects can be misleading and is bad style, so use sizeof(type) Many years ago an int was 16 bits, and programs were written with this assumption. What is the size of integers now sizeof knows the size of array int ar[3]; // Or: int ar[] = 54, 47, 99 sizeof(ar) 12 as well for arrays whose size is determined at run-time: int n = 3; int ar[n]; // Or: int ar[fun_that_returns_3()]; sizeof(ar) 12 Dynamic Memory Allocation (2/4) To allocate room for something new to point to, use malloc() (with the help of a typecast and sizeof): ptr = (int *) malloc (sizeof(int)); Now, ptr points to a space somewhere in memory of size (sizeof(int)) in bytes. (int *) simply tells the compiler what will go into that space (called a typecast). malloc is almost never used for 1 var ptr = (int *) malloc (n*sizeof(int)); This allocates an array of n integers. CS61C L05 Introduction to C (pt 3) (8) Dynamic Memory Allocation (3/4) Once malloc() is called, the memory location contains garbage, so donʼt use it until youʼve set its value. After dynamically allocating space, we must dynamically free it: free(ptr); Use this command to clean up. Even though the program frees all memory on exit (or when main returns), donʼt be lazy! You never know when your main will get transformed into a subroutine! CS61C L05 Introduction to C (pt 3) (9) Dynamic Memory Allocation (4/4) The following two things will cause your program to crash or behave strangely later on, and cause VERY VERY hard to figure out bug free()ing the same piece of memory twice calling free() on something you didnʼt get back from malloc() The runtime does not check for these mistakes Memory allocation is so performance-critical that there just isnʼt time to do this The usual result is that you corrupt the memory allocatorʼs internal structure You wonʼt find out until much later on, in a totally unrelated part of your code! CS61C L05 Introduction to C (pt 3) (10) Arrays not implemented as youʼd think Binky Pointer Video (thanks to NP @ SU) void foo() int *p, *q, x, a[1]; // a[] = 3 also works here p = (int *) malloc (sizeof(int)); q = &x; *p = 1; // p[0] would also work here *q = 2; // q[0] would also work here *a = 3; // a[0] would also work here printf("*p:%u, p:%u, &p:%u\n", *p, p, &p); printf("*q:%u, q:%u, &q:%u\n", *q, q, &q); printf("*a:%u, a:%u, &a:%u\n", *a, a, &a);... 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68... 52 32 2 3 1... p q x a unnamed-malloc-space *p:1, p:52, &p:24 *q:2, q:32, &q:28 *a:3, a:36, &a:36 CS61C L05 Introduction to C (pt 3) (11) CS61C L05 Introduction to C (pt 3) (12)

CS61C L05 Introduction to C (pt 3) (13) Kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta 1. Kid meets giant Texas people exercising zen-like yoga. Rolf O 2. Kind men give ten percent extra, zestfully, youthfully. Hava E 3. Kissing Mentors Gives Testy Persistent Extremists Zealous Youthfulness. Gary M 4. Kindness means giving, teaching, permeating excess zeal yourself. Hava E 5. Killing messengers gives terrible people exactly zero, yo 6. Kindergarten means giving teachers perfect examples (of) zeal (&) youth 7. Kissing mediocre girls/guys teaches people (to) expect zero (from) you 8. Kinky Mean Girls Teach Penis-Extending Zen Yoga 9. Kissing Mel Gibson, Teddy Pendergrass exclaimed: Zesty, yo! Dan G 10. Kissing me gives ten percent extra zeal & youth! Dan G (borrowing parts) Peer Instruction Which are guaranteed to print out 5 I: main() int *a-ptr; *a-ptr = 5; printf( %d, *a-ptr); II: main() int *p, a = 5; p = &a;... /* code; a & p NEVER on LHS of = */ printf( %d, a); III: main() int *ptr; ptr = (int *) malloc (sizeof(int)); *ptr = 5; printf( %d, *ptr); CS61C L05 Introduction to C (pt 3) (14) I II III 0: - - - 1: - - YES 2: - YES - 3: - YES YES 4: YES - - 5: YES - YES 6: YES YES - 7: YES YES YES And in Conclusion Use handles to change pointers Create abstractions with structures Dynamically allocated heap memory must be manually deallocated in C. Use malloc() and free() to allocate and deallocate memory from heap. Reference slides You ARE responsible for the material on these slides (theyʼre just taken from the reading anyway) ; weʼve moved them to the end and off-stage to give more breathing room to lecture! CS61C L05 Introduction to C (pt 3) (15) CS61C L05 Introduction to C (pt 3) (16) C structures : Overview A struct is a data structure composed from simpler data types. Like a class in Java/C++ but without methods or inheritance. struct point /* type definition */ int x; int y; ; void PrintPoint(struct point p) As always in C, the argument is passed by value a copy is made. printf( (%d,%d), p.x, p.y); struct point p1 = 0,10; /* x=0, y=10 */ PrintPoint(p1); C structure Pointers to them Usually, more efficient to pass a pointer to the struct. The C arrow operator (->) dereferences and extracts a structure field with a single operator. The following are equivalent: struct point *p; /* code to assign to pointer */ printf( x is %d\n, (*p).x); printf( x is %d\n, p->x); CS61C L05 Introduction to C (pt 3) (17) CS61C L05 Introduction to C (pt 3) (18)

CS61C L05 Introduction to C (pt 3) (19) How big are structs Recall C operator sizeof() which gives size in bytes (of type or variable) How big is sizeof(p) struct p char x; int y; ; 5 bytes 8 bytes Compiler may word align integer y Letʼs look at an example of using structures, pointers, malloc(), and free() to implement a linked list of strings. /* node structure for linked list */ struct Node ; Recursive definition! CS61C L05 Introduction to C (pt 3) (20) typedef simplifies the code struct Node ; /* "typedef" means define a new type */ typedef struct Node NodeStruct; OR typedef struct Node NodeStruct; THEN typedef NodeStruct *List; typedef char *String; String value; /* Note similarity! */ /* To define 2 nodes */ struct Node node1, node2; /* Add a string to an existing list */ String s1 =, s2 = "cde"; List thelist = ; thelist = cons(s2, thelist); thelist = cons(s1, thelist); /* or, just like (cons s1 (cons s2 nil)) */ thelist = cons(s1, cons(s2, )); CS61C L05 Introduction to C (pt 3) (21) CS61C L05 Introduction to C (pt 3) (22) CS61C L05 Introduction to C (pt 3) (23) CS61C L05 Introduction to C (pt 3) (24)

CS61C L05 Introduction to C (pt 3) (25) "" CS61C L05 Introduction to C (pt 3) (26) CS61C L05 Introduction to C (pt 3) (27) CS61C L05 Introduction to C (pt 3) (28)