David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Structures Often we want to be able to manipulate logical entities as a whole For example, complex numbers, dates, student records, etc Each of these must.
Dynamic memory allocation
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
An introduction to pointers in c
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
1 CSE 303 Lecture 12 structured data reading: Programming in C Ch. 9 slides created by Marty Stepp
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Introduction and a Review of Basic Concepts
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
C FAQ’S Collected from the students who attended technical round in TCS recruitment.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
Pointers OVERVIEW.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
Week 9 - Monday.  What did we talk about last time?  Time  GDB.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Introduction to Data Structures Systems Programming Concepts.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Pointers and Linked Lists
Dynamic Allocation Review Structure and list processing
Pointers and Linked Lists
CSE 374 Programming Concepts & Tools
Pointers.
Introduction to Data Structures
LinkedList Class.
Popping Items Off a Stack Lesson xx
Programming in C Pointer Basics.
Topic 3-b Run-Time Environment
Programming in C Pointer Basics.
C Structures and Memory Allocation
Programming in C Advanced Pointers.
Module 13 Dynamic Memory.
Week 9 - Monday CS222.
Presentation transcript:

David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent

Upcoming schedule CSE303 Au092 Today 10/23 Monday 10/26 Wednesday 10/28 Friday 10/30 Monday 11/2 Finish-up Wednesday Some specifics for HW3 Social implications Friday Memory managementMidterm review Midterm structured data struct, typedef structs as parameters/returns arrays of structs linked data structures stacks linked lists

free : releases memory free(pointer); Releases the memory pointed to by the given pointer –precondition: pointer must refer to a heap- allocated memory block that has not already been freed –it is considered good practice to set a pointer to NULL after freeing int* a = (int*) calloc(8, sizeof(int));... free(a); a = NULL;

Memory corruption If the pointer passed to free doesn't point to a heap-allocated block, or if that block has already been freed, bad things happen –you're lucky if it crashes, rather than silently corrupting something int* a1 = (int*) calloc(1000, sizeof(int)); int a2[1000]; int* a3; int* a4 = NULL; free(a1); // ok free(a1); // bad (already freed) free(a2); // bad (not heap allocated) free(a3); // bad (not heap allocated) free(a4); // bad (not heap allocated)

Structured data struct : A type that stores a collection of variables –like a Java class, but with only fields (no methods or constructors) –instances can be allocated on the stack or on the heap struct Point { // defines a new structured int x, y; // type named Point };

Using structs Once defined, a struct instance is declared just like built-in types (e.g., int, char ) except preceded by struct –this allocates an instance on the stack –name fields of a struct using the. operator struct Point { int x, y; }; int main(void) { struct Point p1; struct Point p2 = {42, 3}; p1.x = 15; p1.y = -2; printf("p1 is (%d, %d)\n", p1.x, p1.y); return 0; }

typedef Tell C to acknowledge your struct type's name with typedef typedef struct Point { int x, y; } Point; int main(void) { Point p1; // don't need to write 'struct' p1.x = 15; p1.y = -2; printf("p1 is (%d, %d)\n", p1.x, p1.y); return 0; }

Structs as parameters when you pass a struct as a parameter, it is copied –not passed by reference as in Java int main(void) { Point p = {10, 20}; swapXY(p); printf("(%d, %d)\n", p.x, p.y); return 0; // prints (10, 20) } void swapXY(Point a) { int temp = a.x; a.x = a.y; a.y = temp; // does not work }

Pointers to structs struct s can be passed using pointers –must use parentheses when dereferencing a struct* (because of operator precedence) int main(void) { Point p = {10, 20}; swapXY(&p); printf("(%d, %d)\n", p.x, p.y); return 0; // prints (20, 10) } void swapXY(Point* a) { int temp = (*a).x; (*a).x = (*a).y; (*a).y = temp; }

The -> operator We often allocate struct s on the heap –pointer->field is equivalent to (*pointer).field int main(void) { Point* p = (Point*) malloc(sizeof(Point)); p->x = 10; p->y = 20; swapXY(p); printf("(%d, %d)\n", p->x, p->y); // (20, 10) return 0; } void swapXY(Point* a) { int temp = a->x; a->x = a->y; a->y = temp; }

Copy by assignment One struct 's entire contents can be copied to another with = – struct2 = struct1; // copies the memory int main(void) { Point p1 = {10, 20}, p2 = {30, 40}; p1 = p2; printf("(%d, %d)\n", p1.x, p1.y); // (30, 40) // is this the same as p1 = p2; above? Point* p3 = (Point*) malloc(sizeof(Point)); Point* p4 = (Point*) malloc(sizeof(Point)); p3->x = 70; p3->y = 80; p3 = p4; printf("(%d, %d)\n", p3->x, p3->y); }

Struct as return value We generally pass/return struct s as pointers –takes less memory (and time) than copying –if a struct is malloc -ed and returned as a pointer, who frees it? int main(void) { Point* p1 = new_Point(10, 20);... free(p1); } // creates/returns a Point; sort of a constructor Point* new_Point(int x, int y) { Point* p = (Point*) malloc(sizeof(Point)); p->x = x; p->y = y; return p; // caller must free p later }

Comparing structs relational operators ( ==, !=,, = ) don't work with structs Point p1 = {10, 20}; Point p2 = {10, 20}; if (p1 == p2) {... // error what about this? Point* p1 = new_Point(10, 20); Point* p2 = new_Point(10, 20); if (p1 == p2) {... // true or false?

Comparing structs, cont'd the right way to compare two structs : write your own #include bool point_equals(Point* a, Point* b) { if (a->x == b->x && a->y == b->y) { return true; } else { return false; } int main(void) { Point p1 = {10, 20}; Point p2 = {10, 20}; if (point_equals(&p1, &p2)) {...

Structs and input you can create a pointer to a field of a struct –structs ' members can be used as the target of a scanf, etc. int main(void) { Point p; printf("Please type your x/y position: "); scanf("%d %d", &p.x, &p.y); } int main(void) { Point* p = (Point*) malloc(sizeof(Point)); printf("Please type your x/y position: "); scanf("%d %d", &p->x, &p->y); }

Arrays of structs parallel arrays are conceptually linked by their index –parallel arrays are usually bad design; isn't clear that they are related –you should often replace such arrays with an array of structs int id[50]; // parallel arrays to store int year[50]; // student data (bad) double gpa[50]; typedef struct Student { int id, year; double gpa; } Student; Student students[50];

Structs with pointers What if we want a Student to store a significant other? typedef struct Student { // incorrect.. Why? int id, year; double gpa; struct Student sigother; } Student; When to stop the recursion? –a Student cannot fit another entire Student inside of it!

Alternative typedef struct Student { // correct int id, year; double gpa; struct Student* sigother; } Student; CSE303 Au0918

Linked data structures C does not include collections like Java's ArrayList, HashMap –must build any needed data structures manually –to build a linked list structure, create a chain of structs/pointers typedef struct Node { int data; struct Node* next; } Node; Node* front =...; datanext 10 datanext 990 NULL front... datanext 20

Manipulating a linked list there is only a node type ( struct ), no overall list class list methods become functions that accept a front node pointer: int list_length(Node* front) { Node* current = front; int count = 0; while (current != NULL) { count++; current = current->next; } return count; } datanext 10 datanext 30 NULL front datanext 20

Exercise Write a complete C program that allows the user to create a basic stack of ints. The user should be able to: –push: put a new int onto the top of the stack. –pop: remove the top int from the stack and print it. –clear: remove all ints from the stack. Do not make any assumptions about the size of the stack. –Do not allow any memory leaks in your program.

Questions? CSE303 Au0922