Dynamic Allocation in C

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.
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.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
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 CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
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.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
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.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
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.
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.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
More Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Allocating Arrays Dynamically You allocate an array by.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Windows Programming Lecture 03. Pointers and Arrays.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
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 Storage Allocation
EGR 2261 Unit 11 Pointers and Dynamic Variables
Data Types In Text: Chapter 6.
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Motivation and Overview
ENERGY 211 / CME 211 Lecture 25 November 17, 2008.
Pointers and Memory Overview
Checking Memory Management
Memory and Addresses Memory is just a sequence of byte-sized storage devices. The bytes are assigned numeric addresses, starting with zero, just like the.
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Dynamic Allocation in C
TUTORIAL 7 CS 137 F18 October 30th.
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Dynamic Data Structures
Presentation transcript:

Dynamic Allocation in C The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically, as the program executes. In C, this is accomplished via the Std Library function malloc() and friends: malloc() allocates a block of uninitialized memory; returns the address calloc() allocates a block of memory and clears it; returns the address realloc() resizes a previously allocated block of memory; returns the address int *A = malloc( 1000 * sizeof(int) ); char *B = malloc( 5000 ); uint64_t Size = 100; double *C = malloc( Size * sizeof(double) );

The Heap stack heap stack space dynamic allocations

Allocating Arrays Dynamically You allocate an array by allocating a suitably-sized block of memory: int N; . . . // assume N is assigned a value int *A = malloc( N * sizeof(int) ); // allocate array // dynamically for (int pos = 0; pos < N; pos++) { // access using ptr name A[pos] = pos * pos; } Any pointer name can be used with array syntax (bracket notation)… but you'd better make sure that the pointee really is an array.

Dynamic Allocation Failure It is always possible that an allocation request will be denied; in that case, malloc() and friends will return NULL. A deadly sin is to not check the return value from malloc() to be sure it isn't NULL: int *A = malloc( 1000 * sizeof(int) ); if ( A == NULL ) { fprintf(stderr, "Failed to allocate space for A!\n"); exit(1); } Without the check of A, the subsequent code will probably lead to a runtime error (unless there was no need for the array).

Deallocation in C One of the most glaring differences between Java and C is how memory deallocation is accomplished. In C, we have static allocations, local or automatic allocations, and dynamic allocations. The first two are of no particular interest here. Everything that your C program allocates dynamically must eventually be deallocated. The responsibility is yours. Failure to deallocate memory in a timely but safe manner is one of the most common programming mistakes in many languages, including C. Deallocation is accomplished by using the Std Library function free(): int *A = malloc( 1000 * sizeof(int) ); . . . free(A); free() does not reset the value of the pointer on which it is invoked!

C free() It's important to understand just what free() does (and does not do). First, free() can only be applied to a pointer storing the address of a target that was allocated by calling malloc() and friends. Second, free() can only be applied to a pointer whose a target that has not already been deallocated. Third, when free() is invoked on a pointer, the pointer is not automatically reset to NULL. Fourth, free() causes the deallocation of the target of the pointer, not the deallocation of the pointer itself. You don't free a pointer, you free its target.

Array Names vs Pointers So, what's the difference between an array name (static allocation) and a pointer? int N; . . . // assume N is assigned a value int *A = malloc( 1000 * sizeof(int) ); // allocate array int B[1000]; // declare array for (int pos = 0; pos < N; pos++) { // access using ptr name A[pos] = pos * pos; B[pos] = pos * pos; } free( A ); // OK; deallocates array A A = NULL; // OK free( B ); // NO! cannot deallocate static memory B = NULL; // NO! array name is const pointer

Array Notation vs Pointers int A[1000]; . . . int x = A[10]; int *B = malloc(1000*sizeof(int)); . . . int x = *(B + 10); B index address 1000 1 1004 1008 10 1040 B + 10 Really means: B + 10 * sizeof(int)

Arithmetic on Pointers So, what's the effect of: int A[1000]; // allocate array; static doesn’t matter int *p = A; // p points to A[0] p = p + 100; // where does p point now?? p = p – 50; // now? p++; // now? p--; // now? The effect of adding a value to a pointer depends on the pointer type:

Arithmetic on Pointers The effect of adding a value to a pointer depends on the pointer type: When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

Using Arithmetic on Pointers Here's an implementation of a variation of the C library strlen() function; note the use of pointer arithmetic: uint64_t strlen(const char* Source) { uint64_t Length = 0; while ( *Source != '\0' ) { Length++; Source++; } return Length; 43 'C' 6F 'o' 6D 'm' 70 'p' 4F 'O' 72 'r' 67 'g' 00 '\0' Source Length: 0, 1, 2, 3, ..., 7

Using Arithmetic on Pointers And here's a slightly more idiomatic version: uint64_t strlen(const char* Source) { uint64_t Length = 0; while ( *Source++ != '\0' ) Length++; return Length; } Precedence note: the dereference operator (*) is evaluated before the increment operator (++) So, we access the current target of Source first, then we move Source to the next array element.

Using Arithmetic on Pointers Here's an implementation of the C library strcpy() function: void strcpy(char* Dest, const char* Source) { int i = 0; while ( true ) { Dest[i] = Source[i]; if (Dest[i] == '\0') break; // we're done i++; }

Using Arithmetic on Pointers And here's a version that uses pointer arithmetic to achieve the same effect: void strcpy(char* Dest, const char* Source) { while ( (*Dest++ = *Source++) != '\0' ) ; } 43 'C' 6F 'o' 6D 'm' 70 'p' 4F 'O' 72 'r' 67 'g' 00 '\0' Dest Source

Identity vs Equality Revisited x equals y x and y, in some precise sense, have the same value In C, this is equivalent to x == y. x is identical to y x and y are actually the same object In C, this is equivalent to &x == &y. Side notes: If x and y are pointers, then x equals y if and only if x and y have the same target. In other words, two pointers are equal if and only if their targets are identical.

Memory Leaks A memory leak occurs when a process allocates memory dynamically and then fails to deallocate that memory before losing access to it: int *p = malloc(1000 * sizeof(int)); . . . p = malloc(1500 * sizeof(int)); // leaked original array p = NULL; // leaked second array Memory leaks are common in badly-written C/C++ code. Taken to extremes, they can consume all available memory on a system. Garbage-collected memory management automates the process of deallocation, but can never be more efficient than well-written code that deallocates memory manually.

Memory Leaks One issue you'll encounter in testing is that the Linux implementation of malloc() will zero memory when it is allocated to your process. That hides errors rather than fixing them. For better testing, add the following include: #include <malloc.h> Then in main() add this call:  mallopt(M_PERTURB, 205); This will guarantee that memory that is allocated with malloc() or realloc() is NOT automatically written with zeros. We recommend ALWAYS doing this when you're testing code that uses malloc() or realloc().

The Key to Good Memory Management The key to good memory management practice can be stated quite easily: In designing your system, keep careful track of exactly who (i.e., module or function) has ownership of each dynamically-allocated object. Practicing this is not easy. But, with careful attention to detail, and meticulous recording of design decisions about ownership in comments, it is certainly possible to eliminate memory leaks altogether.