March, 2006 Saeid Nooshabadi

Slides:



Advertisements
Similar presentations
CS61C L04 Introduction to C (pt 2) (1) Garcia, Fall 2011 © UCB Reference slides You ARE responsible for the material on these slides (they’re just taken.
Advertisements

CS61C L03 Introduction to C (pt 2) (1) Garcia, Fall 2006 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CS 61C L04 C Pointers (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2007 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS61C L3 C Pointers (1) Garcia, Fall 2005 © UCB Lecturer PSOE, new dad Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS61C L3 C Pointers (1) Beamer, Summer 2007 © UCB Scott Beamer, Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 – C Strings,
CS61C L04 Introduction to C (pt 2) (1) Garcia, Fall 2011 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2008 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
1 Programming & Programming Languages Overview l Machine operations and machine language. l Example of machine language. l Different types of processor.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS 61C L03 C Pointers (1)Garcia / Patterson Fall 2002 © UCB CS61C - Machine Structures Lecture 3 C pointers  Dan Garcia (
CS61C L3 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 – More C intro,
CS61CL L01 Introduction (1) Huddleston, Summer 2009 © UCB Jeremy Huddleston inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers.
CS 61C L04 C Pointers (1) Garcia, Spring 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CS61C L4 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 –C Strings,
Arrays and Pointers in C Alan L. Cox
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
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.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Topic 4: C Data Structures CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
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.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver 1.
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2010 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
CSE 220 – C Programming malloc, calloc, realloc.
Eighth Lecture Exception Handling in Java
Dynamic Allocation in C
EGR 2261 Unit 11 Pointers and Dynamic Variables
Computer Organization and Design Pointers, Arrays and Strings in C
Motivation and Overview
ENEE150 Discussion 07 Section 0101 Adam Wang.
C Programming Tutorial – Part I
COSC 220 Computer Science II
Run-time organization
March, 2006 Saeid Nooshabadi
Checking Memory Management
Lecture 6 C++ Programming
Circular Buffers, Linked Lists
C help session: Tonight 306 Soda
CS399 New Beginnings Jonathan Walpole.
Dynamic Memory Allocation
Memory Allocation CS 217.
CS61C - Machine Structures Lecture 4 C Structures Memory Management
Pointers.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chapter 16 Pointers and Arrays
Chien-Chung Shen CIS/UD
Pointers and Arrays Beyond Chapter 16
Data Structures and Algorithms Introduction to Pointers
Course Overview PART I: overview material PART II: inside a compiler
Chapter 9: Pointers and String
SPL – PS2 C++ Memory Handling.
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

March, 2006 Saeid Nooshabadi saeid@unsw.edu.au ELEC2041 Microprocessors and Interfacing Lecture 3: C-Language Review - II http://webct.edtec.unsw.edu.au/ March, 2006 Saeid Nooshabadi saeid@unsw.edu.au

Overview Common Pointer Mistakes Pointer Arithmetic Arrays Dynamic Memory Allocation

Review: Pointers in C (#1/2) An address refers to a particular memory location. In other words, it points to a memory location. Pointer: High Level Language (in this case C) way of representing a memory address. More specifically, a C variable can contain a pointer to something else. It actually stores the memory address that something else is stored at.

Review: Pointers in C (#2/2) Why use pointers? If we want to pass a huge struct or array, it’s easier to pass a pointer than the whole thing. In general, pointers allow cleaner, more compact code. So what are the drawbacks? Pointers are probably the single largest source of bugs in software, so be careful anytime you deal with them.

Review: Pointers & Allocation (#1/2) After declaring a pointer: int *ptr; ptr doesn’t actually point to anything yet. We can either: make it point to something that already exists, or allocate room in memory for something new that it will point to… (next time)

Review: Pointers & Allocation (#2/2) Pointing to something that already exists: int *ptr, var1, var2; var1 = 5; ptr = &var1; var2 = *ptr; var1 and var2 have room implicitly allocated for them.   ptr ? 5 ? ? 5 var1 var2

All Tools included in the Companion CD-ROM Review: ELEC2041 Software Edit Utility Tools Enable creation of C or assembly source programs for ARM Processor on a Linux Platform GNU ARM Cross Compiler and Assembler Tools: Enable Translation by Compilation, Assembly, and Linking of source programs into ARM object programs; Executable and Linking Format (ELF) GNU ARM Source Level Debugger Enables simulation of ARM ELF programs while referencing back to the source code. Komodo Integrated Debugger Enables downloading of ARM ELF code into the target ARM Processor on DSLMU Development Board Enables Execution and debugging of the downloaded program on the target processor on DSLMU Development Board All Tools included in the Companion CD-ROM

C Pointer Dangers (#1/2) Declaring a pointer just allocates space to hold the pointer – it does not allocate something to be pointed to! Local variables in C are not initialized, they may contain anything. What does the following code do? void f() { int *ptr; *ptr = 5; }

int x = 1000; C Pointer Dangers (#2/2) Unlike Java, C lets you cast a value of any type to any other type without performing any checking. int x = 1000; int *p = x; /* invalid */ int *q = (int *) x; /* valid */ The first pointer declaration is invalid since the types do not match. The second declaration is valid C but is almost certainly wrong Is it ever correct? ? Address:1000 q x 1000

Pointer Arithmetic (#1/5) 80 24 Since a pointer is just a memory address, we can add to it to traverse an array. ptr+1 will return a pointer to the next array element. ptr 65 a[1] 81 Ptr + 1 82 32 a[2] Ptr + 2 83 90 a[3] 84 45 a[4] 85 55 a[5] 86 11 a[6] 87 88 a[7] char a[8]; 100 - 103 80

Pointer Arithmetic (#2/5) 80 24 a[0] What about array of integers (4 Byte size). ptr+1 will return a pointer to the next integer array element as well. ptr a[1] 65 84 Ptr + 1 32 a[2] 88 Ptr + 2 90 a[3] 92 45 a[4] 96 100 55 a[5] 104 11 a[6] 108 a[7] 88 int a[8]; 100 - 103 80

Pointer Arithmetic (#3/5) Struc #1 24 80 What if we have an array of large structs? C takes care of it: In reality, ptr+1 doesn’t add 1 to the memory address, but rather adds the size of an array element. ptr 65 b c 32 90 d 45 a Struc #2 96 Ptr + 1 b 55 11 c 88 d Struc #n 100 - 103

Pointer Arithmetic (#4/5) C knows the size of the thing a pointer points to – every addition or subtraction moves that many bytes. So the following are equivalent: int get(int array[], int n) { return (array[n]); /* OR */ return *(array + n); }

Pointer Arithmetic (#5/5) So what’s valid pointer arithmetic? Add an integer to a pointer. Subtract 2 pointers (in the same array). Compare pointers (<, >, etc.). Compare pointer to NULL (indicates that the pointer points to nothing). Everything else is illegal since it makes no sense: adding two pointers, multiplying pointers subtract pointer from integer

Pointer Arithmetic Peer Instruction Which one of the following are invalid? – pointer + integer – integer + pointer – pointer + pointer – pointer – integer – integer – pointer – pointer – pointer – compare pointer to pointer – compare pointer to integer – compare pointer to 0 OK Not OK Not OK OK Not OK OK OK Not OK OK

Pointer Usage (#1/2) 80 84 88 92 96 100 104 108 var var2 ptr 80 84 88 var 5 ? var2 ptr 80 84 88 92 96 100 104 108 var ? var2 ptr 80 84 88 92 96 100 104 108 var 5 ? var2 ptr 80 84 88 92 96 100 104 108 var 5 var2 ptr Once a pointer is declared: use & to return a pointer to an existing variable (the memory address of the variable) use * to return the value pointed to by a pointer variable Example: int *ptr, var, var2; var = 5; ptr = &var; var2 = *ptr;

Pointer Usage (#2/2) Since a pointer is just a mem address, we can add to it to traverse an array. p+1 returns a ptr to the next array element (*p)+1 vs *p++ vs *(p+1) vs (*p)++ ? x = (*p)+1  x = *p +1; p = p; p x +1 x = *p++  x = *p ; p = p + 1; p x +1 x = *(p+1)  x = *(p+1) ; p = p; p x x = (*p)++  x = *p ; *p = *p + 1; p x +1

Dynamic Memory Allocation (#1/4) After declaring a pointer: int *ptr; ptr doesn’t actually point to anything yet. We can either: make it point to something that already exists, or allocate room in memory for something new that it will point to…

Dynamic Memory Allocation (#2/4) Pointing to something that already exists: int *ptr, var, var2; var = 5; ptr = &var; var2 = *ptr; var and var2 have room implicitly allocated for them.

Dynamic Memory Allocation (#3/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.

Dynamic Memory Allocation (#4/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.

¥ C memory allocation Space for saved procedure information Stack Address ¥ Stack Space for saved procedure information sp stack pointer Heap Explicitly created space, e.g., malloc(); C pointers global pointer gp Static Variables declared once per program Code Program

An Example of embedded system: Playstation III Cells contains a CPU, and eight vector processors (SPE) each with 128K of memory. Runs at 4GHz, producing 256Gflops, Connected to the central 64MB memory through a switched 1024 bit bus. 6.4Gb/s of-chip bandwidth 1.3 V power supply The Graphic Accelerator (RSX) chip connects directly to the Cell. Represents 1500 person years of investment Delivers two teraflops of power when it's coupled to the Cell. Contain 300 million transistors (Pentium has 100 million)

GO to the Tutorial Classes: Key to Success in ELEC2041 Doing the Lab Experiments and Weekly Tutorial sets, and On-line quizzes on the WebCT diligently, properly and honestly. Last year all students who failed the course got less than 50% in quiz and less than 60% in the lab. GO to the Tutorial Classes: We go through the problems similar to quiz from the previous week in the tutorial session.

Projects@EELC2041 Dots-and-Boxes Games Arnon Politi, in June 2004 Dots and Boxes is a familiar pencil-and-paper game that most of us used to play as children. It starts from a square array of dots where each of the two players, in turn, has to connect any adjacent dots with a line, either horizontally or vertically. Whenever a player closes the forth side of a box he initials that box and must then play again. The game goes on until all of the boxes had been initialed and the player who initialed more boxes is declared as the winner. Arnon Politi, in June 2004

Arrays (#1/6) Declaration: int ar[2]; declares a 2-element integer array. int ar[] = {795, 635}; declares and fills a 2-element integer array. Accessing elements: ar[num]; returns the numth element.

Arrays are (almost) identical to pointers char *string and char string[] are nearly identical declarations They differ in very subtle ways: incrementing, declaration of filled arrays Key Concept: An array variable is a “pointer” to the first element.

Arrays (#3/6) Consequences: int ar[8]; ar is a pointer ar[0] is the same as *ar ar[2] is the same as *(ar+2) We can use pointer arithmetic to access arrays more conveniently. int ar[8]; 80 24 ar[0] ar ar[1] 65 84 32 ar[2] 88 90 ar[3] 92 45 ar[4] 96 100 55 ar[5] 104 11 ar[6] Declared arrays are only allocated while the scope is valid char *foo() { char string[32]; ...; return string; } is incorrect 108 ar[7] 88 100 - 103 80

Arrays (#4/6) Array size n; want to access from 0 to n-1, but test for exit by comparing to address one element past the array int ar[10], *p, *q, sum = 0; ... p = &ar[0]; q = &ar[10]; while (p != q) /* sum = sum + *p; p = p + 1; */ sum += *p++; Is this legal? C defines that one element past end of array must be a valid address, i.e., not cause an bus error or address error

Why? SINGLE SOURCE OF TRUTH Arrays (#5/6) Array size n; want to access from 0 to n-1, so you should use counter AND utilize a constant for declaration & incr Wrong int i, ar[10]; for(i = 0; i < 10; i++){ ... } Right #define ARRAY_SIZE 10 int i, a[ARRAY_SIZE]; for(i = 0; i < ARRAY_SIZE; i++){ ... } Why? SINGLE SOURCE OF TRUTH You’re utilizing indirection and avoiding maintaining two copies of the number 10

Segmentation faults and bus errors: Arrays (#6/6) Pitfall: An array in C does not know its own length, & bounds not checked! Consequence: We can accidentally access off the end of an array. Consequence: We must pass the array and its size to a procedure which is going to traverse it. Segmentation faults and bus errors: These are VERY difficult to find; be careful!

Segmentation Fault vs Bus Error? http://www.hyperdictionary.com/ Segmentation Fault A fatal failure in the execution of a machine language instruction resulting from the processor detecting an anomalous condition on its bus. Such conditions include invalid address alignment (accessing a multi-byte number at an odd address), accessing a physical address that does not correspond to any device, or some other device-specific hardware error. A bus error triggers a processor-level exception which Unix translates into a “SIGBUS” signal which, if not caught, will terminate the current process. Bus Error An error in which a running Unix program attempts to access memory not allocated to it and terminates with a segmentation violation error and usually a core dump.

C Strings (#1/2) A C String is just an array of characters: char *str = “hello”; str points to the ‘h’ The next five elements are: ‘e’, ‘l’, ‘l’, ‘o’, and NULL (‘\0’) Key Detail: A C String is always terminated with a NULL, which is why they’re called null-terminated strings. str[0] 80 ‘h’ str ‘e’ str[1] 81 82 ‘l’ str[2] 83 ‘l’ str[3] 84 ‘o’ str[4] 85 str[5] 100 - 103 80

How do you tell how long a string is? C Strings (#2/2) How do you tell how long a string is? Last character is followed by a 0 byte (null terminator) int strlen(char s[]) { int n = 0; while (s[n] != 0) n++; return n; }

C Strings Headaches One common mistake is to forget to allocate an extra byte for the null terminator. More generally, C requires the programmer to manage memory manually (unlike Java or C++). When creating a long string by concatenating several smaller strings, the programmer must insure there is enough space to store the full string! What if you don’t know ahead of time how big your string will be? Buffer overrun security holes!

Common Pointer Mistakes (#1/2) 80 84 88 92 96 100 104 108 ? p Declare and write: int *p; *p = 10; /* WRONG */ What address is in p? Answer: NULL; C defines that memory address 0 (same as NULL) is not valid to write to. Remember to malloc first.

Common Pointer Mistakes (#2/2) 80 84 88 92 96 100 104 108 92 ip 92 iq 200 a 200 b 80 84 88 92 96 100 104 108 ? ip ? iq 100 a 200 b 80 84 88 92 96 100 104 108 88 ip 92 iq 100 a 200 b 80 84 88 92 96 100 104 108 88 ip 92 iq 200 a 200 b Copy pointers vs. values: int *ip, *iq, a = 100, b = 200; ip = &a; iq = &b; *ip = *iq; /* what changed? */ ip = iq; /* what changed? */

References: Nick Parlante: Stanford CS Education Library (http://cslibrary.stanford.edu/); A Collection of very useful material including: Essential C: (http://cslibrary.stanford.edu/101/) A relatively quick, 45 page discussion of most of the practical aspects of programming in C. Binky Pointer Video: (http://cslibrary.stanford.edu//104) Silly but memorable 3 minute animated video demonstrating the basic structure, techniques, and pitfalls of using pointers. Pointer Basics: (http://cslibrary.stanford.edu/106) The companion text for the Binky video. Pointers and Memory: (http://cslibrary.stanford.edu/102) A 31 page explanation of everything you ever wanted to know about pointers and memory. Linked List Basics: (http://cslibrary.stanford.edu/103) A 26 page introduction to the techniques and code for building linked lists in C.

Things to Remember (#1/2) Common Pointer problems Declare and write Copy pointers vs. values

Things to Remember (#2/2) Use malloc and free to allow a pointer to point to something not already in a variable. An array name is just a pointer to the first element. A string is just an array of chars.