C Programming : Dynamic memory allocation & Structures 2008/11/19 Made by Jimin Hwa Edited and presented by Souneil Park

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Dynamic memory allocation
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
C Programming : Elementary Data Structures 2009/04/22 Jaemin
Kernighan/Ritchie: Kelley/Pohl:
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:
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
Linked Lists. Array Limitations Arrays have a fixed size that cannot be changed at run time What if your program had an array to store info regarding.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
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.
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.
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
Chapter 14 Dynamic Data Structures Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Lecture 13 Static vs Dynamic Memory Allocation
7. Pointers, Dynamic Memory 20 th September IIT Kanpur 1C Course, Programming club, Fall 2008.
Stack and Heap Memory Stack resident variables include:
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
ECE Application Programming
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Data Structure & Algorithms
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
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.
Stack and Heap Memory Stack resident variables include:
Linked List :: Basic Concepts
5.13 Recursion Recursive functions Functions that call themselves
CSCI206 - Computer Organization & Programming
Dynamic Memory Allocation
14th September IIT Kanpur
CSC215 Lecture Memory Management.
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Linked List.
CS111 Computer Programming
7. Pointers, Dynamic Memory
EECE.2160 ECE Application Programming
C Programming Lecture-8 Pointers and Memory Management
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Dynamic Data Structures
Presentation transcript:

C Programming : Dynamic memory allocation & Structures 2008/11/19 Made by Jimin Hwa Edited and presented by Souneil Park

Contents Dynamic memory allocation Structure Linked list 2

Motivation of Dynamic Allocation The allocated space of an array is not flexible What if more space is required? Data insertion/deletion is difficult 3 char []“CC510” int []

Dynamic Memory Allocation malloc Allocates size bytes and returns a pointer to the allocated memory. 4 int *pi; int size, i; scanf(“%d”, &size); pi = (int *)malloc(sizeof(int) * size); // (type): static type casting for (i = 0; i < size; i++)// Initialization pi[i] = -1; void* malloc(size_t size) /* : malloc/calloc/realloc */

Dynamic Memory Allocation (Cont’d) calloc – initializes memory before allocation Allocates size bytes, initialize the space with 0, and returns a pointer to the allocated memory 5 void* calloc(size_t nmeb, size_t size) int *pi; int size, i; scanf(“%d”, &size); pi = (int *)calloc(size, sizeof(int)); // (type): static type casting

Dynamic Memory Deallocation Synopsis Frees the memory space pointed by ptr. Frees(deallocates) the dynamically allocated memory space 6 void free(void *ptr) /* : free */ int *pi; int size, i; scanf(“%d”, &size); pi = (int *)malloc(sizeof(int) * size); if (pi != NULL) { free(pi); pi = NULL; }

Structure A structure is a collection of variables, possibly of different types, grouped together under a single name. Using structure, we can keep together different pieces of information as a single data record Data packing mechanism Example> structure student attributes: Name, student ID, and grade 7

Structure(Cont’d) 8 struct student { /* struct struct_name{ */ char name[32]; /* definition of members */ intstudent_id; /* }; */ chargrade; }; struct class { struct student member[100]; int num_of_students; int average_grade; }; int main(){ struct class CC510; /* struct struct_name var_name */ … }

Structure Operators Operator for member access : “.” (dot) connects the structure name and the member name structure_name.member Example> struct student john; john.grade = ‘A’; john.student_id = 4473; int id = john.student_id; operator for member access (pointer) : -> Exmple> struct student *pJohn; pJohn->grade = ‘A’; // (*pJohn).grade = ‘A’; pJohn->student_id = 4473; int id = john->student_id; 9

Structure Operators(Cont’d) Assignment between structure variable: “=“ Example> 10 struct student John; struct student John_clone; John.name = “John”; John.grade = ‘A'; John.student_id = ; John_clone = John; /* John_clone.name = = “John”, John_clone.grade = = ‘A‘, John_clone.student_id = = */

Structure Comparison We need to compare all fields one by one explicitly. Example> 11 if(john == john_clone){ … } /* Wrong */ if(strcmp(John.name, john_clone.name) == 0 && John.student_id == john_clone.student_id && …){…} /*Right */

Structure as a Function Argument They are passed to functions by the usual parameter-passing mechanism The entire structure is copied to the function Example> 12 int fail(struct student of_classA[], int size) { int i, count = 0; for (i=0; i < size; ++i){ if(of_class[i].grade == ‘F’) count ++; } return count }

Linked List An alternative to array. Data structure in which objects are arranged in a linear order Consists of nodes, each containing arbitrary data fields and link pointing to the next nodes. The size of a linked list would be changed in runtime Node LinkData field HEAD X

Linked List Implementation An node is represented in a C structure. malloc() is used to dynamically create node structure 14 typedef struct node_t { int data; struct _node_t *next; } node_t; node_t head; head.next = NULL; /* Linked list is empty */ node_t* create_node(int d) { node_t *n = (node_t*)malloc( sizeof(node_t)); if (!n) return NULL; n->data = d; n->next = NULL; return n; }

LAB #7 - 1 Implement a circular list Get input from users (through standard input) Input is an integer Whenever a user enters an positive integer, Store the input at the last First, print the 1 st, 3 rd, 5 th, … element Then, print the 2 nd, 4 th, 6 th, … element If zero or a negative integer is entered, terminate the program. 15

LAB #7 - 2 Implement a clist_copy function which copies the circular list (struct xxx *) clist_copy (struct xxx *head) { …. } Which returns the head of the copied circular list In the main function, Print the head address of the original list and the copied list Print the elements of the copied circular list in a sequential order 16

The End Any Question? 17