Low-Level C Programming. Memory map Pointers Arrays Structures

Similar documents
Pointers, Dynamic Data, and Reference Types

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

Understanding Pointers

Kurt Schmidt. October 30, 2018

CS C Primer. Tyler Szepesi. January 16, 2013

ECE 15B COMPUTER ORGANIZATION

Q1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics

Dynamic Data Structures. CSCI 112: Programming in C

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

Quiz 0 Review Session. October 13th, 2014

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

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

Cpt S 122 Data Structures. Data Structures

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

BBM 201 DATA STRUCTURES

Intermediate Programming, Spring 2017*

Character Strings. String-copy Example

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CS61C : Machine Structures

CS 241 Data Organization Binary Trees

CSCI 171 Chapter Outlines

CSC 1600 Memory Layout for Unix Processes"

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

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

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

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012

Heap Arrays. Steven R. Bagley

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

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

Lectures 5-6: Introduction to C

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);!

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

Lectures 13 & 14. memory management

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

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Dynamic Memory: Alignment and Fragmentation

Memory Management in C (Dynamic Strings) Personal Software Engineering

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

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

Under the Hood: Data Representations, Memory and Bit Operations. Computer Science 104 Lecture 3

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Lecture 8 Dynamic Memory Allocation

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

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

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

Memory, Data, & Addressing II CSE 351 Spring

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

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

2. dead code elimination (declaration and initialization of z) 3. common subexpression elimination (temp1 = j + g + h)

Data Structures and Algorithms for Engineers

Lecture Notes on Memory Layout

CA341 - Comparative Programming Languages

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

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

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

CS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models

Data Representation and Storage. Some definitions (in C)

Memory Management. CS31 Pascal Van Hentenryck CS031. Lecture 19 1

1d: tests knowing about bitwise fields and union/struct differences.

ECE 2035 A Programming Hw/Sw Systems Spring problems, 8 pages Final Exam Solutions 29 April 2015

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Memory Allocation. General Questions

Class Information ANNOUCEMENTS

Limitations of the stack

Lectures 5-6: Introduction to C

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

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

Arrays and Memory Management

CS61 Section Notes. Section 5 (Fall 2011) Topics to be covered Common Memory Errors Dynamic Memory Allocation Assignment 3: Malloc

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

Operating System Labs. Yuanbin Wu

Programs in memory. The layout of memory is roughly:

Pointers and Arrays 1

INTRODUCTION 1 AND REVIEW

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers

CS61C : Machine Structures

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

Dynamic memory allocation (malloc)

Intermediate Programming, Spring 2017*

Recitation #11 Malloc Lab. November 7th, 2017

CSE351 Autumn 2013 Final Exam (11 Dec 2013)

Arrays and Pointers (part 1)

Faux Midterm 1: Review Session

Process s Address Space. Dynamic Memory. Backing the Heap. Dynamic memory allocation 3/29/2013. When a process starts the heap is empty

CS61C : Machine Structures

UW CSE 351, Winter 2013 Final Exam

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

Do not start the test until instructed to do so!

Processes. Johan Montelius KTH

CS201- Introduction to Programming Current Quizzes

ECE 2035 A Programming Hw/Sw Systems Fall problems, 8 pages Final Exam 8 December 2014

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

COMPSCI 210 Part II Data Structure

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

Data Structures and Algorithms for Engineers

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Transcription:

Low-Level C Programming Memory map Pointers Arrays Structures

Memory Map 0x7FFF_FFFF Binaries load at 0x20000 by default Stack start set by binary when started Stack grows downwards You will need one stack for each task 0x0002_0000 0x0000_0000 stack loaded binary

Binaries 0x7FFF_FFFF Code All functions of your program Static data Global variables Static variables Initialized Uninitialized/zeroed All loaded into memory at startup 0x0002_0000 0x0000_0000 stack z i code

Variables 0x7FFF_FFFF All variables have an address Stack auto variables allocated when function called varies with each function call Global variables z/i areas fixed for entire execution of program 0x0002_0000 0x0000_0000 stack z i code

Functions 0x7FFF_FFFF All functions have an address code area fixed for entire execution of program 0x0002_0000 stack z i code 0x0000_0000

Heap 0x7FFF_FFFF For dynamic memory allocation Allocated at need Explicit functions malloc Not mandatory in your project! 0x0002_0000 stack heap z i code 0x0000_0000

Pointers Basic pointer

Pointer Variable that contains address Of another variable Global Stack Of dynamically allocated memory Must be given something to point at Declaring a pointer does not do this Always initialize a pointer!

Basic pointer int a // variable int b int *p // pointer to int a = 7 // a=7 p = &a // p points to a b = *p // b=a=7 *p = 5 // a=5, b=7 &a p a b

Pointer to pointer int a // variable int b int *p // pointer to int int **q // ptr to ptr to int a = 7 // a=7 p = &a // p points to a q = &p // q points to p b = *p // a=7, b=7 *p = 5 // a=5, b=7 **q = 3 // a=3, b=7 &a q p a b

Pointer to pointer int a // variable int b int *p // pointer to int int **q // ptr to ptr to int p = &a // p points to a q = &p // q points to p *q = &b // repoint p to b *p = 1 // b=1 &p &a &b q p a b

Pointers & types Pointer points to a particular type Can only legally address objects of that type Assign char* to int* is an error Each type has a size char = 1 byte short int = 2 bytes int = 4 bytes (on MIPS32) etc.

Pointers & types Special pointer type: void Compatible with all types Use with care! Cannot be dereferenced! What is the type of the object? None!

Arrays Identical things in a row

Basic arrays int a[6] // array int b a[0] = 1 // assign element b = a[2] // read element a[b] = a[5] // variable index a[17] = 2 // danger! Notes zero-based indexing no bounds checking higher index=higher address a[5] a[4] a[3] a[2] a[1] a[0] b

Array initializers Initialize & size array int a[]={1,1,2,3,5,8,13} 7 elements equivalent size: a[7] 13 8 5 3 2 1 1

Arrays = pointers p In C, array == pointer Array variable = address of first element of array int a[6] // array int b int *p p = a p = &a[0] // equivalent // p = &b would point to b a[5] a[4] a[3] a[2] a[1] a[0] b

Arrays = pointers p Index from pointer int a[6] // array int b int *p p = a b = (*p)[5] // () needed! b = *p // b=a[0] a[5] a[4] a[3] a[2] a[1] a[0] b

Arrays = pointers p Indexing = arithmetic a[x] == *(a+x) int a[6] // array int b int *p, *q q = p+3 // q=&a[3] q++ // step to next b = *q // b=a[4] b = *(p+1) // b=a[1] b = q-p // pointer difference a[5] a[4] a[3] a[2] a[1] a[0] b q

Pointer Arithmetic 0x001C Unit of operation: size of type int *p char *q p++ p++ q++ q++ p q 3 2 17 \0 o l l e h 0x0018 0x0014 0x0010 0x000C 0x000B 0x000A 0x0009 0x0008 0x0007

sizeof sizeof operator defined in C Gives the size in #of bytes of a type Used to step pointers

Arrays of pointers p int *r[6] // array of ptr int *p int b int a p = &a r[3] = &b *r[3] = 7 // b=7 r[4] = p r[5] r[4] r[3] r[2] r[1] r[0] b a

Pointer to array p int (*p)[6] // ptr to array int a[6] p = &a // correct a[5] a[4] a[3] a[2] a[1] a[0]

Strings p String = array of char Special initializer syntax No other support in C Null-terminated char s[] = hello char *p p = s *p = w // s[0]=w *p = s[4] // s[0]=o s[5] s \0 o l l e h

Array of Strings there Array of char* Each string separate Stored in constant memory Not contiguous char *s[]={ hello, there, a } hello a s[2] s[1] s[0]

Arrays as parameters Passed as pointer, not value No check for size of array void foo(char a[]) { int i; for(i=0;i<max_size;i++) {...a[i]... } }

Arrays as parameters Pointer is alternative, equivalent void foo(char *a, int b) { int i; for(i=0;i<b;i++) {...a[i]......*a++... } }

Iterating over Strings Compute the length of a string: Watch for the zero termination! int length (const char * s) { char *p=s; while( *p!= '\0' ) p++; return p-s; }

Local Arrays Allocated on the stack Not cleared before use Always initialize Contains garbage data when created Deallocated when function returns Do not return a local pointer!

Structures Organizing data into records

Structures in C Collection of related data Use typedef for clarity Syntax: typedef struct TAG { // TAG is optional but good form TYPE element; TYPE2 element2;... } TAG_T; TAG_T x; // declare variable

In Memory Elements stored in order Potentially padded To align evenly in memory Towards higher addresses struct bar { char a; // 1 byte // invisible 3-byte padding int b; // 4 bytes int *c; // 4 bytes x c cb a 0x0008 0x0004 0x0000 } x;

Structs typedef struct { int i; char c; } S_t ; S_t s int a = 112 char b = y s.i = a s.c = x b = s.c s b a i c

Struct Pointers S_t s S_t t S_t *p p = &s // p points at s (*p).i = t.i // assign element p->i = t.i // special syntax! t = *p // t=s s t p i c i c

Struct Ptr in Struct typedef struct T { int i; struct T *p; // ptr to own type } T_t T_t s T_t t T_t *q // struct T* q q = &s q->p = &t // changing s.p t.p = s.p // t points to itself s t q i p i p

Structure Parameters Call-by-value Gets copied to the stack of the callee void foo(struct bar x, int b) {...x.a... }

Structure Initialization Initialize all elements of a struct struct bar z = { a, 45, &b}; Combine with array initializers struct bar z[3] = { { a, 45, &b}, { b, 47, &c}, { d, 10, &d} }

Linked Lists Structs + Pointers

Linked list Head pointer Points at first element in list Outside the list per se Next pointer Points to the next element Stored inside the list End marked by NULL Elements are structs in C p

Defining a list Element type: typedef struct T { int value; // short: v struct T *next; // short: n } T_t Head pointer: T_t *head head = NULL head

First element Create a new element Declare as variable Allocate dynamically We get a pointer to it T_t e T_t *q e.n = NULL // initialize! q = &e // ptr to newcomer e h v n q

Insert into list Update head head = q // q = &e // ptr to newcomer First element Special case e v n q h

One more Link in at start of list Update head But first new element points at the old head of the list! T_t f // new element f.n = NULL // initialize next q = &f q->n = h h = q e f v n v n q h

Traverse a list Visit all elements Start at head Use a walker T_t *w // walker w = h // start while(w!=null) { visit(w) w = w->next } w f e v n v n h

Remove element Link over the element Change the predecessor Special case for head! Unlink it from the list Make removed element have NULL next pointer p

Remove element Example function void remove( T_t *e ) { if (h==e) h = h->next; else { T_t *w = h; while(w!=null) { if(w->next == e) w->next = w->next->next; w = w->next; } } e->next = NULL; } w p

Arrays of Structures

Array of Structures T_t a[4] T_t t = {10,NULL} T_t *p a[0] = t p = a+2 // p = &a[2] *p = t a[1] = a[3] p v n v n v n v n

Static Memory Global array of struct: Statically allocated Gives you a memory area to work on Good alternative to malloc() in OS

Exercises To work on to familiarize yourself with pointeres

Exercises Work on Sun/Linux/Windows Get it right on host first! Use malloc() to create elements T_t *p = malloc( sizeof(t_t) ) Use printf() to see contents of lists

Sorted linked list Create a linked list that is always sorted, with the following functions: newelement(value): creates a new element using malloc() insert(list,newelement): inserts the new element in the right place in the list delete(list,element): removes the element from the list print(list): print the list

Double-linked lists Each element has two pointers: next and previous Basic functions to create: No requirements for sorting here! newelement(value) insert(list,newelement) insert_after(list,element,newelement) delete(list,element) print(list,direction)

Linked list in array Declarea largearray T_t a[1000] Instead of malloc(), allocate new elements from unused array items Thread the linked list through the array

Linked list in array Two lists: Used elements Unused/free elements Allocate = move from free to used Find a free item Relink to the other list