CS24 Week 2 Lecture 1

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

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

ECE 15B COMPUTER ORGANIZATION

CS61C : Machine Structures

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

CS61C : Machine Structures

CS61C : Machine Structures

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

Dynamic Allocation of Memory

CSC 1600 Memory Layout for Unix Processes"

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

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

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

CS 222: Pointers and Manual Memory Management

Fall 2018 Discussion 2: September 3, 2018

CS 11 C track: lecture 6

Week 6 Part 1. Kyle Dewey. Monday, July 30, 12

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

Week 7 Part I. Kyle Dewey. Monday, August 6, 12

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Dynamic Data Structures. CSCI 112: Programming in C

EL2310 Scientific Programming

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

C Introduction. Comparison w/ Java, Memory Model, and Pointers

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

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Advanced Pointer Topics

Dynamic memory allocation (malloc)

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS 11 C track: lecture 5

COMPSCI 210 Part II Data Structure

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

Data Representation and Storage. Some definitions (in C)

Lectures 13 & 14. memory management

Arrays and Pointers. CSE 2031 Fall November 11, 2013

C Characters and Strings

CS C Primer. Tyler Szepesi. January 16, 2013

CS 61c: Great Ideas in Computer Architecture

Lecture Notes on Types in C

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

Dynamic Memory Allocation and Linked Lists

Dynamic Allocation of Memory

CS61C : Machine Structures

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Welcome! COMP s1. Programming Fundamentals

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Class Information ANNOUCEMENTS

CS61C : Machine Structures

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:

EL2310 Scientific Programming

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Pointers and Memory Management

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

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

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Dynamic Memory Management

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

Arrays and Pointers (part 2) Be extra careful with pointers!

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

C Structures & Dynamic Memory Management

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

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

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

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Intermediate Programming, Spring 2017*

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

Memory (Stack and Heap)

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

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

DAY 3. CS3600, Northeastern University. Alan Mislove

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

Heap Arrays and Linked Lists. Steven R. Bagley

CS201- Introduction to Programming Current Quizzes

Review! Lecture 5 C Memory Management !

CS61C : Machine Structures

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

Memory Management. CSC215 Lecture

Arrays and Pointers (part 2) Be extra careful with pointers!

Structures and Pointers

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CS61C : Machine Structures

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

CS 2461: Computer Architecture I: Heap: Dynamic Memory Allocation Data Structures. Recap. Variables and Structures

Data Representation and Storage

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

High Performance Programming Programming in C part 1

Pointers, Dynamic Data, and Reference Types

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Section Notes - Week 1 (9/17)

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

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

Transcription:

CS24 Week 2 Lecture 1 Kyle Dewey

Overview C Review Void pointers Allocation structs

void* (Void Pointers)

void* Like any other pointer, it refers to some memory address However, it has no associated type, and cannot be dereferenced directly Question: why can t it be dereferenced?

No Dereferencing void* p = 2; *p; // get what s at p Value 0x21 0x00 0x01 0x52 0xF0 0xAB 0x2C Address 0 1 2 3 4 5 6 void* is a value without context Without context, there is no way to know how to interpret the value (int? char? double?)

How to Use a void* A void* cannot be dereferenced directly However, it is possible to cast a void* to another type char* str = moo ; void* p = str; printf( %s\n, (char*)p );

How to Use a void* A void* also coerces into other pointer types char* str = moo ; void* p = str; char* str2 = p; // no errors

Caveat A void* also coerces into other pointer types The compiler will trust you blindly char* str = moo ; void* p = str; // no compiler errors, but // this is probably not what // is desired int* nums = p;

Why a void*? Allows for generic data structures A list of ints looks a lot like a list of chars Can refer to some block of memory without context Up next: why anyone would want to do that

Dynamic Memory Allocation

Motivation We want to read in a dictionary of words Before reading it in: We don t know how many words there are apple We don t know how big each word is banana pear <<empty>> aardvark

Possible Solution Allocate the maximum amount you could ever need Question: why is this generally not a good solution? (2 reasons) // 1000 words max with // 100 characters max per word char dictionary[1000][100];

Problems Most things do not have a good maximum you can get a grasp of Your program always needs the maximum amount of memory, and usually the vast majority is completely wasted

What is Desired A way to tell the computer to give a certain amount of memory to a program as it runs Only what is explicitly requested is allocated

Dynamic Memory Allocation Dynamic: as the program runs Memory allocation: set aside memory

malloc The most generic way to allocate memory Takes the number of bytes to allocate Returns a void* to the block of memory allocated // size_t is an integral defined // elsewhere void* malloc( size_t numbytes );

Using malloc The sizeof operator comes in handy Returns an integral size as a size_t For example: allocate room for 50 integers dynamically: // dynamically int* nums1; nums1 = malloc( sizeof( int ) * 50 ); int nums2[ 50 ]; // statically

Question Why did we malloc with sizeof(int) instead of sizeof(int*)? We assigned it to an int*, after all int* nums1; nums1 = malloc( sizeof( int ) * 50 );

Answer We wanted room for 50 integers, not integer pointers int* nums1; nums1 = malloc( sizeof( int ) * 50 );

Importance Static allocation can only be done with constants Dynamic allocation can be done with variables int numtoallocate; scanf( %i, &numtoallocate ); int* nums = malloc(sizeof( int ) * numtoallocate); int nums2[ numtoallocate ]; // ERROR

Memory Contents The contents of the memory allocated by malloc is undefined You will need to initialize it yourself with a loop (or by using the memset function)

free Once we are done using a block of memory, call free on it If a block is never freed, it is called a memory leak Memory is still allocated but wasted int* nums; nums = malloc( sizeof( int ) * 50 );... // done with nums free( nums );

malloc1.c, malloc2.c

On Calling free With static allocation, the compiler handles deallocation for you With dynamic allocation, you must call free yourself The simple act of knowing when to call free can be hard In general, mathematically unsolvable!

Memory-Related Bugs What is wrong with this code? int* foo() { int x = 7; return &x; } void bar() { int* p = foo(); *p = 8; }

Memory-Related Bugs What is wrong with this code? int* foo() { int x = 7; return &7; Space for x is deallocated when foo returns } Who knows what p points to? void bar() { int* p = foo(); *p = 8; (undefined) } Called a dangling pointer

Memory-Related Bugs What is wrong with this code? void foo() { int* p = (int*)malloc(sizeof(int)); *p = 7; free(p); *p = 8; }

Memory-Related Bugs What is wrong with this code? void foo() { int* p = (int*)malloc(sizeof(int)); *p = 7; free(p); *p = 8; p is deallocated, then used. Called a use after free }

Memory-Related Bugs What is wrong with this code? void foo() { int* p = (int*)malloc(sizeof(int)); *p = 7; }

Memory-Related Bugs What is wrong with this code? void foo() { int* p = (int*)malloc(sizeof(int)); *p = 7; p is allocated, but never } deallocated. This is a memory leak.

structs

Question What is a struct?

Basic Idea A way to group a fixed number of items, of potentially different types Arrays: multiple items of the same type A way to create whole new datatypes

Example // defining typedef struct _person { char* name; char* address; int phone; } person;... // using struct _person p1; person p2, p3;

Questions typedef struct _person { char* name; char* address; int phone; } person;... person p; How do I access p s phone field? How do I update p s name field?

Answers typedef struct _person { char* name; char* address; int phone; } person;... person p; p.phone p.name = NULL

Passing structs structs are copied when passed to functions struct blah { int x; }; void foo(struct blah b) { b.x = 7; } int main() { struct blah p; p.x = 1; foo(p); printf("%d", p.x); // prints what? return 0; }

Passing structs structs are copied when passed to functions struct blah { int x; }; void foo(struct blah b) { b.x = 7; } int main() { struct blah p; p.x = 1; foo(p); printf("%d", p.x); // prints 1 return 0; }

Passing structs Often passed via pointer, since they tend to be at least of moderate size Avoids copying

Pointers to structs Dealing with pointers to structs can get obnoxious because of parentheses struct blah { int x; }; void foo(struct blah* b) { } (*b).x = 7;

Pointers to structs Can alleviate this with the equivalent arrow operator struct blah { int x; }; void foo(struct blah* b) { (*b).x = 7; b->x = 8; }

Question How might we allocate a struct?

Answer How might we allocate a struct? struct blah { int x; };... struct blah* b = malloc(sizeof(struct blah));

Question What about an array of size n of structs? struct blah { int x; };

Answer What about an array of size n of structs? struct blah { int x; };... struct blah* arr = malloc(sizeof(struct blah) * n); arr[3].x = 7; // n > 3

Putting it All Together (If Time Allows)

Problem Description We have a file in the following format: 3 Apple Giraffe Hover First line is the number of words, and subsequent lines are words Each word is 20 characters or less

Problem Read it into an array of type char** (an array of strings) Dynamic allocation must be used

Related Problem Read it into an array of type char* (a single string) Dynamic allocation must be used How do we access individual strings?