Dynamic Memory Allocation

Similar documents
Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

5 Arrays and Pointers

Sources: On the Web: Slides will be available on:

The C Programming Language course syllabus associate level

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Module 816. File Management in C. M. Campbell 1993 Deakin University

How To Write Portable Programs In C

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

System Calls and Standard I/O

Stacks. Linear data structures

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Illustration 1: Diagram of program function and data flow

arrays C Programming Language - Arrays

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Passing 1D arrays to functions.

C Interview Questions

Lecture 22: C Programming 4 Embedded Systems

Java Interview Questions and Answers

Introduction to Java

File Handling. What is a file?

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Embedded Systems Design Course Applying the mbed microcontroller

Simple C Programs. Goals for this Lecture. Help you learn about:

C++ Programming Language

Leak Check Version 2.1 for Linux TM

Answers to Review Questions Chapter 7

Senem Kumova Metin & Ilker Korkmaz 1

Lecture 5: Java Fundamentals III

The programming language C. sws1 1

Comparing RTOS to Infinite Loop Designs

Tutorial on C Language Programming

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Example 1/24. Example

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Basics of I/O Streams and File I/O

CP Lab 2: Writing programs for simple arithmetic problems

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

MatrixSSL Porting Guide

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

How To Write An Array In A Microsoft Zil

Chapter One Introduction to Programming

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Computer Science 2nd Year Solved Exercise. Programs 3/4/2013. Aumir Shabbir Pakistan School & College Muscat. Important. Chapter # 3.

Unit 6. Loop statements

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

public static void main(string[] args) { System.out.println("hello, world"); } }

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Pitfalls in Embedded Software

System Calls Related to File Manipulation

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Chapter 13 Storage classes

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

An Incomplete C++ Primer. University of Wyoming MA 5310

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Introduction to Programming II Winter, 2014 Assignment 2

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

Java Types and Enums. Nathaniel Osgood MIT April 25, 2012

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

An Implementation of a Tool to Detect Vulnerabilities in Coding C and C++

Arrays in Java. Working with Arrays

1 Abstract Data Types Information Hiding

Purify User s Guide. Version 4.1 support@rational.com

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Fondamenti di C++ - Cay Horstmann 1

/* File: blkcopy.c. size_t n

(hours worked,rateofpay, and regular and over time pay) for a list of employees. We have

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

C++ INTERVIEW QUESTIONS

Building Embedded Systems

Microcontroller Systems. ELET 3232 Topic 8: Slot Machine Example

Introduction to Java. CS 3: Computer Programming in Java

Shared Memory Segments and POSIX Semaphores 1

Informatica e Sistemi in Tempo Reale

COSC282 BIG DATA ANALYTICS FALL 2015 LECTURE 2 - SEP 9

Introduction to Data Structures

How To Understand How A Process Works In Unix (Shell) (Shell Shell) (Program) (Unix) (For A Non-Program) And (Shell).Orgode) (Powerpoint) (Permanent) (Processes

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

So far we have considered only numeric processing, i.e. processing of numeric data represented

Data Structures using OOP C++ Lecture 1

Comp151. Definitions & Declarations

C PROGRAMMING FOR MATHEMATICAL COMPUTING

8.5. <summary> Cppcheck addons Using Cppcheck addons Where to find some Cppcheck addons

6.S096 Lecture 1 Introduction to C

EXEC SQL CONNECT :userid IDENTIFIED BY :passwd;

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Java from a C perspective. Plan

Buffer Overflows. Code Security: Buffer Overflows. Buffer Overflows are everywhere. 13 Buffer Overflow 12 Nov 2015

ONE OF THE MOST JARRING DIFFERENCES BETWEEN A MANAGED language like PHP,

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Static Code Analysis Procedures in the Development Cycle

C++FA 5.1 PRACTICE MID-TERM EXAM

RTI Monitoring Library Getting Started Guide

Transcription:

Dynamic Memory Allocation Dynamic memory allocation How to allocate memory for variables (esp. arrays/strings) during run time malloc(), calloc(), realloc(), and free() 1

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? 2

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 <stdlib.h> 3

malloc() char *charp; /* declare a pointer to char */ charp charp = malloc(10); 10 bytes or chars charp charp contains the address of the beginning of that block. 4

free() The function free() returns memory to the memory pool. It frees up memory Syntax: free(ptr) where ptr pointsto to memorypreviously allocatedby malloc() function To use free(), you must #include <stdlib.h> 5

Example This program allows the user to specifythe length of a string, allocates memory for the string, and then applies string operations 6

#include <stdlib.h> /* you need this library for malloc(), free(), exit() */ #include <stdio.h> #include <string.h> /* you need this library for strchr(), strlen() */ int main () char *charp, *q; int maxlen; printf("enter maximum string length: "); scanf("%d" %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); 7 A

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. 8

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. 9

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. 10

int main () Example char *charp, r[80]; int length; Memory leak example 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); */ 11 B

int main () Example char *charp, r[80]; int length; while (1) 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. 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); */ 12

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. 13

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! 14

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? */ 15

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)); 16 C

allocate int and double array int *intp; double *doublep; // Allocate space for 10 integers intp = malloc(10 * sizeof(int)); Allocates 40 bytes sizeof(int) = 4 // Allocate space for 10 doubles doublep = malloc(10 * sizeof(double)); Allocates 80 bytes sizeof(double) = 8 17

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! 18

int main () double *dblptr; int howmany, randnum; Step 1: Prompt the user to enter the number of random numbers to generate printf("how many random numbers to generate:"); howmany=processinput(stdin); dblptr = malloc(howmany * sizeof(double)); if (dblptr == NULL) printf("memoryallocation error, exiting\n"); exit(1); An example program for (int i=0;i<howmany;i++) randnum = random(); dblptr[i]=(randnum%10000)/1000.0; 0; PrintArray(dblPtr,howMany); 19

int main () double *dblptr; int howmany, randnum; Step 2: create a dynamic array to store the random numbers 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); In this example we have tested to be sure malloc succeeded. If not, we are out of memory. for (int i=0;i<howmany;i++) randnum = random(); dblptr[i]=(randnum%10000)/1000.0; 0; PrintArray(dblPtr,howMany); 20

int main () double *dblptr; int howmany, randnum; Step 3: generate the random numbers and print them 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; 0; PrintArray(dblPtr,howMany); 21

dblptr = realloc(dblptr, 2*howMany); Step 4: double the size of the array using realloc for (int i=howmany; i<howmany*2; i++) randnum = random(); dblptr[i]=(randnum%10000)/1000.0; Step 5: generate more random numbers and print them howmany *= 2; PrintArray(dblPtr, howmany); free(dblptr); 22

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 23

Print Array void PrintArray(double *ptr, int cnt) printf("printing Array Values\n"); for(double *p=ptr; p p<ptr+cnt; p p++) printf("val is:%lf\n",*p); 24 1