CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.

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

Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Dynamic memory allocation
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.
COMP 1402 Winter 2009 Tutorial #8 malloc / calloc / realloc.
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.
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.
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
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.
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{
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
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 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
C Tokens Identifiers Keywords Constants Operators Special symbols.
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.
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.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
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.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
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.
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.
CSE 220 – C Programming malloc, calloc, realloc.
Stack and Heap Memory Stack resident variables include:
Advanced Programming with C
CSCI206 - Computer Organization & Programming
Programming and Data Structures
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Dynamic Memory Allocation
CS111 Computer Programming
Memory Allocation CS 217.
Dynamic Memory Allocation
EECE.2160 ECE Application Programming
Review & Lab assignments
CS111 Computer Programming
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
C Programming Lecture-8 Pointers and Memory Management
Comp 208 Computers in Engineering Yi Lin Fall, 2005
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Module 13 Dynamic Memory.
Presentation transcript:

CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated

Dynamic Memory Allocation Dynamic memory allocation is used to obtain and release memory during program execution. Up until this point we reserved memory at compile time using declarations. You have to be careful with dynamic memory allocation. It operates at a low- level, you will often find yourself having to do a certain amount of work to manage the memory it gives you. To use the functions discussed here, you must include the stdlib.h header file. Four Dynamic Memory Allocation Functions: Allocate memory - malloc(), calloc(), and realloc() Free memory - free()

malloc() To allocate memory use void *malloc(size_t size); Takes number of bytes to allocate as argument. Use sizeof to determine the size of a type. Returns pointer of type void *. A void pointer may be assigned to any pointer. If no memory available, returns NULL. e.g. char *line; int linelength = 100; line = (char*)malloc(linelength);

malloc() example To allocate space for 100 integers: int *ip; if ((ip = (int*)malloc(100 * sizeof(int))) == NULL){ printf("out of memory\n"); exit(); } Note we cast the return value to int*. Note we also check if the function returns NULL.

Allocating memory for a struct You can also allocate memory for a struct. Example: struct node *newPtr; newPtr = (struct node *)malloc(sizeof(struct node)); Memory allocated with malloc() lasts as long as you want it to. It does not automatically disappear when a function returns, as automatic-duration variables do, but it does not have to remain for the entire duration of your program, either. There is a mechanism to free allocated memory.

free() To release allocated memory use free() Deallocates memory allocated by malloc(). Takes a pointer as an argument. e.g. free(newPtr); Freeing unused memory is a good idea, but it's not mandatory. When your program exits, any memory which it has allocated but not freed will be automatically released.

calloc() Similar to malloc(), the main difference is that the values stored in the allocated memory space are zero by default. With malloc(), the allocated memory could have any value. calloc() requires two arguments - the number of variables you'd like to allocate memory for and the size of each variable. void *calloc(size_t nitem, size_t size); Like malloc(), calloc() will return a void pointer if the memory allocation was successful, else it'll return a NULL pointer.

calloc() example /* Using calloc() to initialize 100 floats to 0.0 */ #include #define BUFFER_SIZE 100 int main(){ float * buffer; int i; if ((buffer = (float*)calloc(BUFFER_SIZE, sizeof(float))) == NULL){ printf("out of memory\n"); exit(1); } for (i=0; i < BUFFER_SIZE; i++) printf(“buffer[%d] = %f\n”, i, buffer[i]); return 0; }

realloc() If you find you did not allocate enough space use realloc(). You give realloc() a pointer (such as you received from an initial call to malloc()) and a new size, and realloc does what it can to give you a block of memory big enough to hold the new size. int *ip; ip = (int*)malloc(100 * sizeof(int));... /* need twice as much space */ ip = (int*)realloc(ip, 200 * sizeof(int));

Variations on struct: union and bit field Union can hold data of different types sharing the same starting address New keyword union Bit Field Up to now the smallest unit we worked with was a char (1 byte) but with the struct keyword you can declare and use smaller objects which allows you to declare and use a single bit. There is no new keyword

union data type (1) This is a special data type which looks similar to a struct used for low-level programming (e.g hardware devices). Memory that contains a variety of objects over time. Only contains one data member at a time. Members of a union share space. Conserves storage. union Number { int x; float y; }; union Number value;

union data type (2) Single memory address used to store the largest variable, unlike the arrangement used for structures. Valid union operations (same as for structs) Assignment to union of same type: = Taking address: & Accessing union members:. Accessing members using pointers: ->

Bit fields in struct Member of a structure whose size (in bits) has been specified. Enable better memory utilization. Must be declared as int or unsigned. Declaring bit fields -follow unsigned or int member with a colon (:) and an integer constant representing the width of the field. Example: struct PlayingCard{ unsigned face:4; unsigned suit:2; unsigned color:1; };