CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings)

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

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.
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.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
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.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
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.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
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:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
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’;
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays 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:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Dynamic memory allocation and Pointers Lecture 4.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
ECE Application Programming
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
Day 03 Introduction to C.
Dynamic Memory Allocation Strings
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Day 03 Introduction to C.
Dynamic Memory Allocation
14th September IIT Kanpur
Programming and Data Structures
CSC215 Lecture Memory Management.
CS111 Computer Programming
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
7. Pointers, Dynamic Memory
EECE.2160 ECE Application Programming
C Programming Lecture-8 Pointers and Memory Management
Chapter 10-1: Dynamic Memory Allocation
Dynamic Memory – A Review
EECE.2160 ECE Application Programming
Presentation transcript:

CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings) during run time – malloc(), calloc(), realloc(), and free()

CSE 251 Dr. Charles B. Owen Programming in C2 Why dynamic memory allocation? Usually, so far, the arrays and strings we’re using have fixed length (i.e., length is known at compile time) Example: char myStr[11]; // allocates memory for 10 chars printf(“Enter a string: “); fgets(myStr, 11, stdin); What if the user wants to enter a string more than 10 chars long or if the length is known only at run time?

CSE 251 Dr. Charles B. Owen Programming in C3 malloc() malloc() is used to request additional memory from the operating system during program execution Syntax: malloc(numBytes) Input is the number of consecutive bytes to be allocated Return value is a pointer to the beginning of the block of memory allocated or NULL if malloc fails To use malloc(), you must #include

CSE 251 Dr. Charles B. Owen Programming in C4 malloc() char *charP; /* declare a pointer to char */ charP charP = malloc(10); charP charP contains the address of the beginning of that block. 10 bytes or chars

CSE 251 Dr. Charles B. Owen Programming in C5 free() The function free() returns memory to the memory pool. It “frees” up memory Syntax: free(ptr) – where ptr “points to” memory previously allocated by malloc() function To use free(), you must #include

CSE 251 Dr. Charles B. Owen Programming in C6 Example This program allows the user to specify the length of a string, allocates memory for the string, and then applies string operations

CSE 251 Dr. Charles B. Owen Programming in C7 #include /* you need this library for malloc(), free(), exit() */ #include #include /* you need this library for strchr(), strlen() */ int main () { char *charP, *q; int maxlen; printf("Enter maximum string length: "); scanf("%d", &maxlen); getchar(); /* reads the newline character */ printf("Enter the string: "); fgets(charP, maxlen, stdin); if ((q = strchr(charP, '\n')) != NULL) *q = '\0'; printf("You've entered a string %s of length %d\n", charP, strlen(charP)); free(charP); } A

CSE 251 Dr. Charles B. Owen Programming in C8 What it does: if ((q = strchr(charP, '\n')) != NULL) *q = '\0'; The function fgets returns the entire line input by the user including the newline at the end (when the user hit return). The function strchr(charP, ‘\n’) will return a pointer to that character (newline) if it exists or NULL otherwise. If the result in the variable q is not NULL, the if statement executes the line of code to replace the newline with a null termination for the string.

CSE 251 Dr. Charles B. Owen Programming in C9 strchr if ((q = strchr(charP, '\n')) != NULL) *q = '\0'; This code finds the first occurance of the character ‘\n’ which is the newline character that fgets will obtain. If found (value in q is not NULL), it sets that character to the string null termination.

CSE 251 Dr. Charles B. Owen Programming in C10 Memory leak If malloc’ed memory is not free’ed, then the OS will “leak memory” – This means that memory is allocated to the program but not returned to the OS when it is finished using it – The program therefore grows larger over time.

CSE 251 Dr. Charles B. Owen Programming in C11 Example int main () { char *charP, r[80]; int length; while (1) { printf("Enter the maximum string length: "); fgets(r, 80, stdin); sscanf(r, "%d", &length); if ((charP = malloc(length)) == NULL) { printf("Out of memory. Quitting\n"); exit(1); } printf("Enter the string: "); fgets(charP, length, stdin); /* free(charP); */ } Memory leak example B

CSE 251 Dr. Charles B. Owen Programming in C12 Example int main () { char *charP, r[80]; int length; while (1) { printf("Enter the maximum string length: "); fgets(r, 80, stdin); sscanf(r, "%d", &length); if ((charP = malloc(length)) == NULL) { printf("Out of memory. Quitting\n"); exit(1); } printf("Enter the string: "); fgets(charP, length, stdin); /* free(charP); */ } Memory leak example Each iteration of the loop allocates memory for a string. But, that memory is never freed. Hence, we have a memory leak.

CSE 251 Dr. Charles B. Owen Programming in C13 malloc without freeing while (1) { charP = malloc(length+1); … } charP If you don’t free the allocated memory, previous block is still “ours” according to the OS, but we can no longer find it (no pointer to it). That block is an orphan! It’s like you bought a house, but then lost the address. You still own it and pay taxes on it, but you can’t use it because you can’t find it.

CSE 251 Dr. Charles B. Owen Programming in C14 Always free what you malloc You are responsible for your memory, you must allocate it and free it. Unlike other languages, it is all up to you! If you don’t free it, your program grows larger and eventually runs out of memory!

CSE 251 Dr. Charles B. Owen Programming in C15 malloc allocates bytes If you want a character array that stores 10 characters (including ‘\0’): char *p = malloc(10); If you want to allocate storage for 10 ints (or doubles or floats), you can’t do this: int *p = malloc(10);/* WRONG! Why? */

CSE 251 Dr. Charles B. Owen Programming in C16 allocate int and double array int *intP; double *doubleP; // Allocate space for 10 integers intP = malloc(10 * sizeof(int)); // Allocate space for 10 doubles doubleP = malloc(10 * sizeof(double)); C

CSE 251 Dr. Charles B. Owen Programming in C17 allocate int and double array int *intP; double *doubleP; // Allocate space for 10 integers intP = malloc(10 * sizeof(int)); // Allocate space for 10 doubles doubleP = malloc(10 * sizeof(double)); Allocates 40 bytes sizeof(int) = 4 Allocates 80 bytes sizeof(double) = 8

CSE 251 Dr. Charles B. Owen Programming in C18 realloc realloc takes a pointer to allocated memory and reallocates the memory to a larger size – if it can make the old block bigger, great – if not, it will get another, larger block, copy the old contents to the new contents, free the old contents and return a pointer to the new intP = malloc(sizeof(int)); intP = realloc(intP, 2*sizeof(intP)); intP may be different after a realloc!

CSE 251 Dr. Charles B. Owen Programming in C19 int main () { double *dblPtr; int howMany, randNum; printf("How many random numbers to generate:"); howMany=ProcessInput(stdin); dblPtr = malloc(howMany * sizeof(double)); if (dblPtr == NULL) { printf("memory allocation error, exiting\n"); exit(1); } for (int i=0;i<howMany;i++) { randNum = random(); dblPtr[i]=(randNum%10000)/1000.0; } PrintArray(dblPtr,howMany); Step 1: Prompt the user to enter the number of random numbers to generate An example program

CSE 251 Dr. Charles B. Owen Programming in C20 Step 2: create a dynamic array to store the random numbers int main () { double *dblPtr; int howMany, randNum; printf("How many random numbers to generate:"); howMany=ProcessInput(stdin); dblPtr = malloc(howMany * sizeof(double)); if (dblPtr == NULL) { printf("memory allocation error, exiting\n"); exit(1); } for (int i=0;i<howMany;i++) { randNum = random(); dblPtr[i]=(randNum%10000)/1000.0; } PrintArray(dblPtr,howMany); In this example we have tested to be sure malloc succeeded. If not, we are out of memory.

CSE 251 Dr. Charles B. Owen Programming in C21 Step 3: generate the random numbers and print them int main () { double *dblPtr; int howMany, randNum; printf("How many random numbers to generate:"); howMany=ProcessInput(stdin); dblPtr = malloc(howMany * sizeof(double)); if (dblPtr == NULL) { printf("memory allocation error, exiting\n"); exit(1); } for (int i=0;i<howMany;i++) { randNum = random(); dblPtr[i]=(randNum%10000)/1000.0; } PrintArray(dblPtr,howMany);

CSE 251 Dr. Charles B. Owen Programming in C22 dblPtr = realloc(dblPtr, 2*howMany); for (int i=howMany; i<howMany*2; i++) { randNum = random(); dblPtr[i]=(randNum%10000)/1000.0; } howMany *= 2; PrintArray(dblPtr, howMany); free(dblPtr); } Step 5: generate more random numbers and print them Step 4: double the size of the array using realloc

CSE 251 Dr. Charles B. Owen Programming in C23 int ProcessInput(FILE *f) { int val; char in[100]; fgets(in,100,f); sscan(in, “%d”, &val); return val; } Safe data entry, just like last week

CSE 251 Dr. Charles B. Owen Programming in C24 Print Array void PrintArray(double *ptr, int cnt) { printf("Printing Array Values\n"); for(double *p=ptr; p<ptr+cnt; p++) printf("Val is:%lf\n",*p); } 1