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.

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

Dynamic memory allocation
Lectures 10 & 11.
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.
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.
Dynamic Memory Allocation
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings)
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
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.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
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:
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{
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Informática II Prof. Dr. Gustavo Patiño MJ
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Lecture 13 Static vs Dynamic Memory Allocation
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,
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
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.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
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.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Computer And Programming Array and Pointer. Array provides a means to allocating and accessing memory. Pointers, on the other hand, provides a way to.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
More Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Allocating Arrays Dynamically You allocate an array by.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
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.
Stack and Heap Memory Stack resident variables include:
CSCI206 - Computer Organization & Programming
Programming Languages and Paradigms
Programming and Data Structures
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Dynamic Memory Allocation
Memory Allocation CS 217.
Dynamic Memory Allocation
CS111 Computer Programming
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
C Programming Lecture-8 Pointers and Memory Management
Chapter 10-1: Dynamic Memory Allocation
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Presentation transcript:

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 allocate memory dynamically Determine size at run time. Allocate at run time.

3 Dynamic Memory Allocation Why allocate memory dynamically? In many cases, we can’t predict in advance what the program will need. May depend on data not known at compile time. May vary dramatically from one run to another. Needed to implement dynamic data structures like linked lists

4 malloc To allocate memory at run time, call the library function malloc(). memory allocation. Function prototype: void* malloc (size_t sz); Number of bytes to allocate (positive integer) A generic pointer Can be used as any pointer type. Optionally typecast as desired pointer type.

5 malloc malloc returns a pointer to the memory that it allocated. Store the returned value in a pointer so that you can use it. malloc can fail! Returns NULL if it cannot allocate the requested amount of memory. Always check for NULL being returned. Normally have to abort the program if this happens.

6 malloc The function declaration for malloc is in stdlib.h. You will need #include

7 Pointers and Arrays When an array declaration like int A[10] is executed, the compiler allocates a block of 10*sizeof(int) bytes; then sets A equal to the address of the first byte of that block Thus the value of A is just &A[0]. Recall that an array variable may not be the left-hand side of an assignment statement Thus, A is effectively a constant pointer

Pointers and Arrays An array name A is effectively a constant pointer Recall that the compiler computes the address of A[i] as A + i*sizeof(sizeof(A[0])) It will do the same with any pointer p in place of A : If p is a pointer, then p[i] is a variable with address p + i*sizeof(*p) Given int A[5] = {5,3,7,1,4}, i; int* p = A; The following are equivalent: for(i=0;i<5;++i) printf(“%d”,A[i] for(i=0;i<5;++i) printf(“%d”,p[i]

Dynamic Arrays We can create an object that acts like an array during program execution as follows: int n, i; int *p; scanf(“%d”,&n); p = malloc(n*sizeof(int)); assert(p != NULL); /* p may now be used as if it were an array name */ for(i = 0; i < n; ++i) scanf(“%d”,&p[i])

10 Example Read a sentence from the keyboard using a large input buffer. Allocate memory to hold the sentence just large enough to hold what was entered. Copy the sentence into the dynamically allocated memory block.

11 Example #include int main() { char input_buffer[1000]; int length = 0; char* sentence = NULL; printf ("Please type a sentence:\n"); fgets(input_buffer, 1000, stdin); printf ("You typed: \n%s\n\n", input_buffer);

12 Example length = strlen(input_buffer); printf ("Allocating %d bytes to hold the sentence\n\n", length+1); sentence = malloc(length+1); assert (sentence != NULL); strcpy (sentence, input_buffer); printf ("The sentence in dynamically allocated memory:\n"); printf ("%s\n", sentence); getchar(); /* Not needed */ getchar(); /* when using CLUE */ return 0; } why +1 ?

13 Program Running

14 Things to Notice Always check the pointer returned by malloc to be sure the malloc was successful. We can make the dynamically allocated memory block any type that we need. Just copy the void* pointer returned by malloc() into a pointer of the desired type. (Some older compilers may require a typecast.)

15 Some C Standard Library Functions for Dynamic Memory Allocation void* malloc (size_t sz ); Returns pointer to uninitialize block of memory of specified size (in bytes) void* calloc (size_t n, size_t sz ); Allocate and clear. Returns pointer to an array of n entries, each of size sz bytes, cleared to binary 0’s. void free (void* pt ); Deallocate block at address pt. Must be a block allocated with malloc or calloc We will discuss this next slides.