Heap Arrays. Steven R. Bagley

Similar documents
Heap Arrays and Linked Lists. Steven R. Bagley

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

Section Notes - Week 1 (9/17)

POINTER AND ARRAY SUNU WIBIRAMA

CSC 1600 Memory Layout for Unix Processes"

My malloc: mylloc and mhysa. Johan Montelius HT2016

Dynamic Data Structures. CSCI 112: Programming in C

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

CS61C Midterm Review on C & Memory Management

Memory (Stack and Heap)

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

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

Lecture 8 Dynamic Memory Allocation

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

Understanding Pointers

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

CS 222: Pointers and Manual Memory Management

Intermediate Programming, Spring 2017*

Data Structure Series

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

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:

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Lectures 13 & 14. memory management

Pointers, Dynamic Data, and Reference Types

Writing Functions in C

Binghamton University. CS-211 Fall Dynamic Memory

CS 11 C track: lecture 5

Dynamic Memory: Alignment and Fragmentation

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

Kurt Schmidt. October 30, 2018

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

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

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CS61C : Machine Structures

CS61C : Machine Structures

Arrays and Memory Management

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

3/7/2018. Sometimes, Knowing Which Thing is Enough. ECE 220: Computer Systems & Programming. Often Want to Group Data Together Conceptually

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

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

EL2310 Scientific Programming

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

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

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

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

Dynamic Memory Allocation and Linked Lists

EL2310 Scientific Programming

Reminder: compiling & linking

Dynamically Allocated Memory in C

Advanced Pointer Topics

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Singly linked lists in C.

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

211: Computer Architecture Summer 2016

Programming in C. Lecture 5: Aliasing, Graphs, and Deallocation. Dr Neel Krishnaswami. Michaelmas Term University of Cambridge

Operating System Labs. Yuanbin Wu

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

CSE351 Spring 2018, Final Exam June 6, 2018

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

CS61C : Machine Structures

Dynamic Memory Management

Review! Lecture 5 C Memory Management !

CS61C : Machine Structures

Pointers and Arrays 1

Structures and Pointers

Character Strings. String-copy Example

Pointers (continued), arrays and strings

Secure Programming I. Steven M. Bellovin September 28,

Fundamental of Programming (C)

CS107, Lecture 9 C Generics Function Pointers

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

Memory Allocation. General Questions

Lecture 16 CSE July 1992

CS61C : Machine Structures

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

Dynamic memory. EECS 211 Winter 2019

Fundamentals of Programming

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

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

Pointers (continued), arrays and strings

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

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

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7

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

A heap, a stack, a bottle and a rack. Johan Montelius HT2017

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

ME964 High Performance Computing for Engineering Applications

DAY 3. CS3600, Northeastern University. Alan Mislove

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

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

EL2310 Scientific Programming

Data Representation and Storage. Some definitions (in C)

CS 2113 Software Engineering

Procedures, Parameters, Values and Variables. Steven R. Bagley

G52CPP C++ Programming Lecture 9

Low-Level C Programming. Memory map Pointers Arrays Structures

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

Transcription:

Heap Arrays Steven R. Bagley

Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double, etc. Create our own data structures

Reading Path from File Could also read the points from a file Until we get the line stop Use fscanf() and see whether it works Or we could use fgets() to read a line Compare with stop If not, use sscanf to process the string And loop... Go implement Show some examples

Out of Memory Problem with this routine What if the number of points in the file is greater than the size of the array? Program will CRASH! Could stop when we fill the array But that would leave half the picture undrawn

Compile-time Memory Problem is that we set the size of the array at compile-time Size is fixed as the program runs And we don t know what the size of the input is here Have to guess, and hope we have enough space

Run-time Memory It would be better if we could set the size of the array at run-time When we know the size we need Make first line of file the number of points Rather than looking for stop C lets us do this, but its manual

A Program s Memory Need to understand the way a program manages memory Although all memory is identical, the program sees it as several different sections These sections are used for various purposes

Code -- machine code Data + BSS -- global variables, (plus other bits and pieces such as predefined strings) Stack -- local variables (grows downward -- top of stack below bottom!) Heap -- This is where objects live! STACK HEAP DATA + BSS CODE 0x0 Typical Memory layout Explain typical memory layout of a program

Allocating Memory Normally, our variables are created on the stack, and are local to the function Get a pointer to it by using &, the address-of operator Can also allocate memory on the heap The heap is the rest of available memory Only have a pointer to it, no direct access

malloc() C lets us allocate memory by using the malloc() function Returns a pointer to the block of memory Need to specify how many bytes we want to allocate

sizeof() Could calculate the size manual int is 4 bytes, float 4 byes, char 1 byte Add them up, so a struct point would be 8 bytes Error prone C provides the sizeof operator that does it automatically sizeof(struct point) Can ask for the size of any type

malloc() and casting void *malloc(size_t size) allocate size bytes and return a pointer to the address Note void * is a pointer to something, not nothing Need to cast the pointer to the right type before we can use it

Casting Cast a value to another type by putting the type name in brackets before it e.g. to convert a float to int float pi = 3.1415927; int ipi = (int)pi; Will truncate values Can also cast pointers This is very dangerous and very powerful

Allocating memory int *p = (int *)malloc(sizeof(int)); Find the size of a int malloc that many bytes Cast the void * pointer to a int * And store in p This generally safe, although handle with care Always think why am I casting this? Don t cast just to make the errors and warnings go away

Using allocated memory Can use this allocated int like any other pointer to an int But have to access it via the pointer Cannot obtain a variable name for it Can also allocate structs in this fashion

free() When we ve finished with memory, we need to free() it Otherwise, it can t be used for anything else until the program quits But can t free it until we ve finished with it (the program has no more pointers with it) Otherwise, accessing it will cause problem

free() void free(void *ptr) Pass it the pointer to the memory you want freeing Must be allocated via malloc() Afterwards, the variable containing the pointer should be cleared as it is no longer valid

Allocating struct struct point *p = (struct point *) malloc(sizeof(struct point)); Find the size of a struct point malloc that many bytes Cast the void * pointer to a struct point * And store in p This generally safe, although handle with care Always think why am I casting this? Don t cast just to make the errors and warnings go away

Heap structs Can use these allocated blocks just like anything else we ve pointed at p->x = 42.0; p->y = 36.0; struct point pt = *p; Allocating structs on the heap is used a lot Most data is stored on the heap

Arrays on the Heap Arrays are represented by a pointer to the base of the array Each element in the array is laid out in memory sequentially The array operator [] works just as well on a pointer as on an array

Arrays on the Heap If we can malloc space for one thing Then we can malloc space for two things Or three, or four etc Treat that pointer as the base of the array

Arrays on the Heap Find out how big one thing is using sizeof() If we want to allocate space for n things Multiple sizeof() by n Gives us the number of bytes to allocate So an array of 42 ints: int *p = malloc(42 * sizeof(int));

Solving our pictures Don t decide array size at compile-time Create it at run-time using malloc() But how big should it be? Four options

Size of Path Array Option One read through the file twice First time through, count lines until stop Then allocate memory using malloc Then use fseek to go back to the beginning and read again Problem might be reading from something that can t be seeked (e.g stdin)

Size of Path Array Option Two copy data if array gets full Allocate the array of a certain size If we fill it, allocate a new larger array And copy the data over using memcpy Works, but can leave memory fragmented and slows program while copying

Size of Path Array Option three Cheat Rather than putting stop at the end Make the first line contain the number of elements Read that Use value to allocate the array

Size of Path Array Option Four Don t use an Array The problem we have is that an array s size is fixed when created If it needs to grow, we need to create a new one and copy the data So use a different data structure that doesn t have this limitation, such as

The Linked List