Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Similar documents
Memory Management. CSC215 Lecture

Dynamic Data Structures. CSCI 112: Programming in C

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

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

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

Dynamic memory allocation

High Performance Programming Programming in C part 1

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

CS 222: Pointers and Manual Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

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

Understanding Pointers

Content. In this chapter, you will learn:

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

Dynamic Memory Allocation

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Memory (Stack and Heap)

int marks[10]; // fixed size and fixed address No change in Memory address.

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

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

Lecture 8 Dynamic Memory Allocation

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

Dynamic memory allocation (malloc)

C PROGRAMMING Lecture 5. 1st semester

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CS 11 C track: lecture 5

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

MODULE V: POINTERS & PREPROCESSORS

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

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

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

Procedural programming with C

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

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

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

Subject: Fundamental of Computer Programming 2068

Structures, Unions, and Enumerations

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

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

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

dynamic memory allocation

Computer Programming Unit 3

Arrays and Pointers (part 1)

Processes. Johan Montelius KTH

Dynamically Allocated Memory in C

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

A process. the stack

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Arrays, Pointers and Memory Management

Class Information ANNOUCEMENTS

POINTER AND ARRAY SUNU WIBIRAMA

Pointers. Introduction

Intermediate Programming, Spring 2017*

Kurt Schmidt. October 30, 2018

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

Memory Management I. two kinds of memory: stack and heap

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION

Memory, Arrays & Pointers

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

CS 61c: Great Ideas in Computer Architecture

Memory Organization. The machine code and data associated with it are in the code segment

C Structures & Dynamic Memory Management

CS C Primer. Tyler Szepesi. January 16, 2013

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

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

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:

Memory Management. CS449 Fall 2017

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

Quick review pointer basics (KR ch )

CSC 1600 Memory Layout for Unix Processes"

Lecture 3 Memory and Pointers

Variation of Pointers

Memory Allocation in C

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

Arrays and Pointers (part 1)

CS24 Week 2 Lecture 1

Programming in C. 4. Misc. Library Features, Gotchas, Hints and Tips. Dr. Neel Krishnaswami University of Cambridge

Structures and Pointers

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

Fundamental of Programming (C)

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Chapter 11: Pointers

EM108 Software Development for Engineers

Character Strings. String-copy Example

Arrays and Memory Management

ECE 551D Spring 2018 Midterm Exam

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

Advanced Pointer Topics

C Tutorial Pointers, Dynamic Memory allocation, Makefile

CSC 270 Survey of Programming Languages. What is a Pointer?

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

Unit IV & V Previous Papers 1 mark Answers

C Programming Basics II

ECE 15B COMPUTER ORGANIZATION

Lecture 3 Memory and Pointers

14. Memory API. Operating System: Three Easy Pieces

Memory Allocation. General Questions

Dynamic memory. EECS 211 Winter 2019

Transcription:

Chapter 14 Dynamic Data Structures Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. 12-1

Dynamic Data Structure Usually, so far, the arrays and strings we re using have fixed length (i.e., length is known at compile time) E.g. char mystr[11]; // allocates memory for 11 chars printf( Enter a string: ); fgets(mystr, 11, stdin);//includes null character What if the user wants to enter a string more than 10 chars long or if the length is known only at run time? 2

Dynamic Data Structure Memory allocation in C: malloc() calloc() realloc() Deallocates using the free()function. 3

Dynamic Data Structure Dynamic data structure is a structure that can expand and contract as a program executes. The creation and manipulation of dynamic data structures requires use of pointers. A pointer is a variable which stores the memory address of a data value. 4

Comparison of pointer and Nonpointer Variables The actual data value of a pointer variable is accessed indirectly. The actual data value of a non-pointer variable can be accessed directly. Pointer variable Nonpointer variable Reference Explanation Value num A simple variable 3 nump pointer holding a memory address Addr. of the location pointed to *nump Indirect value of nump 3 Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5

Pointer Review A call to a function with pointer parameters may need to use the & operator. e.g., if we have an int variable value1 and f1(int *value), f1(&value1) is a legal call. A pointer can be used to represent an array. e.g., char n[] is equal to char *n. A pointer can also represent a structure. e.g., File * is a pointer to a File structure. 6

Memory Allocation C provides a memory allocation function called malloc, which resides in the stdlib library. This function requires an argument which indicates the amount of memory space needed. The returned data type is (void *) and should be always cast to the specific type. It doesn t clear the memory. 7

Memory Allocation - malloc function Description The C library function allocates the requested memory and returns a pointer to it. Declaration void *malloc(size_t size) Parameters size -- This is the size of the memory block, in bytes. Return Value This function returns a pointer to the allocated memory, or NULL if the request fails. 8

Memory Allocation E.g. //Variable declarations #define STRSIZ 10 typedef struct { } planet_t; #include <stdio.h> #include <stdlib.h> int main() char name[strsiz]; double diameter; /* equatorial diameter in km */ int moons; /* number of moons */ double orbit_time, /* years to orbit sun once */ double rotation_time; /* hours to complete one revolution on axis */ { int *nump; char *letp; planet_t *planetp; planet_t blank_planet = {"", 0, 0, 0, 0}; 9

Memory Allocation //Allocation: nump = (int *) malloc (sizeof (int)); letp = (char *) malloc (sizeof (char)); planetp = (planet_t *) malloc (sizeof (planet_t)); //Assignment: *nump = 307; *letp = Q ; *planetp = blank_planet; 10

Memory Allocation Memory space after allocation Memory space after assignment Pointers Pointers 11

Heap and Stack Heap is the region of memory where function malloc dynamically allocates space for variables. Stack is the region of memory where function data areas are allocated and reclaimed. 12

Memory Allocation - calloc function Description This function allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero. Declaration void *calloc(size_t nitems, size_t size) Parameters nitems -- This is the number of elements to be allocated. size -- This is the size of elements. Return Value This function returns a pointer to the allocated memory, or NULL if the request fails. This function is used to declare dynamic arrays. 13

Free Memory Description The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc. Declaration void free(void *ptr) Parameters ptr -- This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs. Return Value This function does not return any value. Once the memory space is released, we can not access the space again. Otherwise, it is considered as an illegal memory access. 14

//Allocating space for a simple integer variable #include <stdio.h> #include <stdlib.h> int main () { int * p; p = (int *) malloc (sizeof (int)); // partitioning of type int if (p == NULL) // failed to reserve area { printf ("Failed to allocate space for %d bytes", sizeof (int)); return 1; } *p = 150; printf ("%d \n", *p); free (p); // free allocated memory space return 0; } 15

Memory Allocation - realloc function Description The C library function attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc. Declaration void *realloc(void *ptr, size_t size) Parameters ptr -- This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function. size -- This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned. Return Value This function returns a pointer to the newly allocated memory, or NULL if the request fails. 16

//Practicing reallocate function #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; /* Initial memory allocation for 15 characters*/ str = (char *) malloc(15); //For simplicity, we skipped error checking strcpy(str, "tutorialspoint"); printf("string = %s, Address = %p\n", str, str); /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("string = %s, Address = %p\n", str, str); free(str); return(0); } 17

Practicing Dynamic Array Allocation C provides a function calloc which creates an array of elements of any type and initializes the array elements to zero. Function calloc takes two arguments: the number of array elements and the size of one element. E.g., int *array_of_nums; array_of_nums = (int *) calloc(10, sizeof(int)); 18

//Let s create an array in a size according to the user request #include <stdio.h> #include <stdlib.h> int main() { int i, n; int *a; printf("number of elements to be entered:"); scanf("%d",&n); a = (int*)calloc(n, sizeof(int));//allocate required memory and initialize it if (a!=null) { printf("enter %d numbers:\n",n); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("the numbers entered are: "); for(i=0;i<n;i++) printf("%d ",a[i]); } else printf("memory allocation cannot be done."); printf("\n"); return(0); } 19

// realloc example: add an integer array element one by one #include <stdio.h> /* printf, scanf, puts */ #include <stdlib.h> /* realloc, free, exit, NULL */ int main () { int input,n,count = 0; int* numbers = NULL,* more_numbers = NULL; do { printf ("Enter an integer value (0 to end): "); scanf ("%d", &input); count++; more_numbers = (int*) realloc (numbers, count * sizeof(int)); if (more_numbers!=null) { numbers=more_numbers; numbers[count-1]=input; } else { free (numbers); puts ("Error (re)allocating memory"); exit (1); } } while (input!=0); printf ("Numbers entered: "); for (n=0;n<count;n++) printf ("%d ",numbers[n]); free (numbers); free(more_numbers); printf("\n"); return 0; } 20

//This program takes input and outputs everything backwards. //http://forum.codecall.net/topic/51010-dynamic-arrays-using-malloc-and-realloc/ #include <stdio.h> #include <stdlib.h> int main() { char *data,*temp,c; int i; for (i=i-1;i>=0;i--)//in previous loop i s value //was out of array bound putchar(data[i]); // Output data backwards // one character at a time free(data); // Free the pointer return 0; } data=(char *) malloc(sizeof(char)); if (data==null) printf("error allocating memory!\n"); else { printf("enter a sentence:\n"); for (i=0; ;i++) {//infinite loop c=getchar(); if (c=='\n') break; //Program stops reading when user hits return key data[i]=c; // put the character into the data array temp=(char *) realloc(data,(i+2)*sizeof(char)); //Reallocate memory,+2 bec.: 1 for arr. index starts from 0,1 to add arr. elem. if (temp!= NULL ) data=temp; else { free(data); printf("error allocating memory!\n"); return 1; }//else }//for 21

Multiple Pointers to a Cell double *xp, xcopyp; xp=(double *)malloc(sizeof(double)); *xp=49.5; free(xp); xcopyp=*xp; Be careful when releasing memory since the other pointer may still access the memory space. Copyright 2004 Pearson Addison-Wesley. All rights reserved. 22