1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp

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.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Pointers A pointer is a reference to another variable (memory location) in a program –Used to change variables inside a function (reference parameters)
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Memory Allocation Professor Jennifer Rexford COS 217.
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 CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
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.
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’;
David Notkin Autumn 2009 CSE303 Lecture 10 "If it weren't for C, we'd be writing programs in BASI, PASAL, and OBOL."
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Memory Layout C and Data Structures Baojian Hua
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.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
ITEC 352 Lecture 18 Functions in Assembly. Functions + Assembly Review Questions? Project due on Friday Exam –Average 76 Methods for functions in assembly.
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,
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.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
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.
Object-Oriented Programming in C++
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.
Dynamic Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
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.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Dynamic Allocation in C
Day 03 Introduction to C.
CSE 374 Programming Concepts & Tools
CSE 303 Lecture 9 C programming: types, functions, and arrays
ENEE150 Discussion 07 Section 0101 Adam Wang.
Day 03 Introduction to C.
Lecture 6 C++ Programming
Dynamic Memory Allocation
Dynamic Memory Allocation
Memory Allocation CS 217.
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.
Chien-Chung Shen CIS/UD
Dynamic Memory A whole heap of fun….
Dynamic Memory.
CSE 303 Lecture 10 C memory model; stack allocation
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp

2 Lecture summary arrays as parameters and returns  arrays vs. pointers the heap  dynamic memory allocation (malloc, calloc, free)  memory leaks and corruption

3 Process memory layout as functions are called, data goes on a stack dynamic data is created on a heap stack (function calls) available memory heap (dynamically allocated data) global/static variables ("data segment") code instructions ("text segment") 0x xFFFFFFFF address space

4 The sizeof operator #include int main(void) { int x; int a[5]; printf("int=%d, double=%d\n", sizeof(int), sizeof(double)); printf("x uses %d bytes\n", sizeof(x)); printf("a uses %d bytes\n", sizeof(a)); printf("a[0] uses %d bytes\n", sizeof(a[0])); return 0; } Output: int=4, double=8 x uses 4 bytes a uses 20 bytes a[0] uses 4 bytes

5 sizeof continued sizeof(type) or (variable) returns memory size in bytes  arrays passed as parameters do not remember their size #include void f(int a[]); int main(void) { int a[5]; printf("a uses %d bytes\n", sizeof(a)); f(a); return 0; } void f(int a[]) { printf("a uses %2d bytes in f\n", sizeof(a)); } Output: a uses 20 bytes a uses 4 bytes in f

6 Arrays and pointers a pointer can point to an array element  an array's name can be used as a pointer to its first element  you can use [] notation to treat a pointer like an array pointer[i] is i elements' worth of bytes forward from pointer int a[5] = {10, 20, 30, 40, 50}; int* p1 = &a[3]; // refers to a's fourth element int* p2 = &a[0]; // refers to a's first element int* p3 = a; // refers to a's first element as well *p1 = 100; *p2 = 200; p1[1] = 300; p2[1] = 400; p3[2] = 500; Final array contents: {200, 400, 500, 100, 300}

7 Arrays as parameters array parameters are really passed as pointers to the first element  The [] syntax on parameters is allowed only as a convenience // actual code: #include void f(int a[]); int main(void) { int a[5];... f(a); return 0; } void f(int a[]) {... } // equivalent to: #include void f(int* a); int main(void) { int a[5];... f(&a[0]); return 0; } void f(int* a) {... }

8 Returning an array stack-allocated variables disappear at the end of the function  this means an array cannot be safely returned from a method int[] copy(int a[], int size); int main(void) { int nums[4] = {7, 4, 3, 5}; int nums2[4] = copy(nums, 4); // no return 0; } int[] copy(int a[], int size) { int i; int a2[size]; for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; // no } main nums, nums2 available heap global data code copy a, size a2, i

9 Pointers don't help dangling pointer: One that points to an invalid memory location. int* copy(int a[], int size); int main(void) { int nums[4] = {7, 4, 3, 5}; int* nums2 = copy(nums, 4); // nums2 dangling here... } int* copy(int a[], int size) { int i; int a2[size]; for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; } main nums nums2 available heap global data code copy a size a2 i

10 Our conundrum We'd like to have data in our C programs that is:  dynamic(size of array changes based on user input, etc.)  long-lived(doesn't disappear after the function is over)  bigger(the stack can't hold all that much data) Currently, our solutions include:  declaring variables in main and passing as "output parameters"  declaring global variables (do not want)

11 The heap heap (or "free store"): large pool of unused memory that you can use for dynamically allocating data and objects  for dynamic, long-lived, large data  many languages (e.g. Java) place all arrays/ objects on the heap // Java int[] a = new int[5]; Point p = new Point(8, 2); stack a p available heap global data code methods 0x00FD8000 0x00FD30F0 0x00FD8000 0x00FD30F0 0x086D0008 0x086D0004

12 malloc variable = (type*) malloc(size); malloc function allocates a heap memory block of a given size  returns a pointer to the first byte of that memory  you should cast the returned pointer to the appropriate type  initially the memory contains garbage data  often used with sizeof to allocate memory for a given data type // int a[8]; <-- stack equivalent int* a = (int*) malloc(8 * sizeof(int)); a[0] = 10; a[1] = 20;...

13 calloc variable = (type*) calloc(count, size); calloc function is like malloc, but it zeros out the memory  also takes two parameters, number of elements and size of each  preferred over malloc for avoiding bugs (but slightly slower) // int a[8] = {0}; <-- stack equivalent int* a = (int*) calloc(8, sizeof(int)); malloc and calloc are found in library stdlib.h #include

14 Returning a heap array when you want to return an array, malloc it and return a pointer  array will live on after the function returns int* copy(int a[], int size); int main(void) { int nums[4] = {7, 4, 3, 5}; int* nums2 = copy(nums, 4);... return 0; } int* copy(int a[], int size) { int i; int* a2 = malloc(size * sizeof(int)); for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; } main nums nums2 available heap global data code copy a size a2 i

15 NULL NULL: An invalid memory location that cannot be accessed.  in C, NULL is a global constant whose value is 0  if you malloc / calloc but have no memory free, it returns NULL  you can initialize a pointer to NULL if it has no meaningful value  dereferencing a null pointer will crash your program int* p = NULL; *p = 42; // segfault Exercise : Write a program that figures out how large the stack and heap are for a default C program.

16 Deallocating memory heap memory stays claimed until the end of your program garbage collector: A process that automatically reclaims memory that is no longer in use.  keeps track of which variables point to which memory, etc.  used in Java and many other modern languages; not in C // Java public static int[] f() { int[] a = new int[1000]; int[] a2 = new int[1000]; return a2; } // no variables refer to a here; can be freed

17 Memory leaks memory leak: Failure to release memory when no longer needed.  easy to do in C  can be a problem if your program will run for a long time when your program exits, all of its memory is returned to the OS void f(void) { int* a = (int*) calloc(1000, sizeof(int));... } // oops; the memory for a is now lost

18 free free(pointer); releases the memory pointed to by the given pointer  precondition: pointer must refer to a heap-allocated memory block that has not already been freed int* a = (int*) calloc(8, sizeof(int));... free(a);  it is considered good practice to set a pointer to NULL after freeing free(a); a = NULL;

19 Memory corruption if the pointer passed to free doesn't point to a heap-allocated block, or if that block has already been freed, bad things happen int* a1 = (int*) calloc(1000, sizeof(int)); int a2[1000]; int* a3; int* a4 = NULL; free(a1); // ok free(a1); // bad (already freed) free(a2); // bad (not heap allocated) free(a3); // bad (not heap allocated) free(a4); // bad (not heap allocated) you're lucky if it crashes, rather than silently corrupting something