Memory Management. CSC215 Lecture

Similar documents
Dynamic memory allocation

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

o Code, executable, and process o Main memory vs. virtual memory

CSC 1600 Memory Layout for Unix Processes"

In Java we have the keyword null, which is the value of an uninitialized reference type

Lecture 8 Dynamic Memory Allocation

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Memory (Stack and Heap)

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Dynamic Memory Allocation

14. Memory API. Operating System: Three Easy Pieces

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Content. In this chapter, you will learn:

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Class Information ANNOUCEMENTS

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Dynamically Allocated Memory in C

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations

CSC 270 Survey of Programming Languages. What is a Pointer?

C PROGRAMMING Lecture 5. 1st semester

C Structures & Dynamic Memory Management

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Dynamic Data Structures. CSCI 112: Programming in C

Computer Programming Unit 3

Understanding Pointers

Fundamental of Programming (C)

ch = argv[i][++j]; /* why does ++j but j++ does not? */

CS 11 C track: lecture 5

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Dynamic Allocation of Memory Space

Secure Coding in C and C++

POINTER AND ARRAY SUNU WIBIRAMA

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

int marks[10]; // fixed size and fixed address No change in Memory address.

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Dynamic memory allocation (malloc)

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

Memory Management. CS449 Fall 2017

Dynamic Allocation of Memory

Arrays and Memory Management

ESc101: Pointers and Arrays

MODULE 5: Pointers, Preprocessor Directives and Data Structures

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Dynamic Memory Allocation and Linked Lists

Secure Coding in C and C++ Dynamic Memory Management Lecture 5 Jan 29, 2013

Intermediate Programming, Spring 2017*

Memory Allocation. General Questions

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Dynamic Allocation in C

Character Strings. String-copy Example

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

ECE551 Midterm Version 2

Memory Management I. two kinds of memory: stack and heap

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Secure Software Programming and Vulnerability Analysis

Dynamic Memory Management

Processes. Johan Montelius KTH

A process. the stack

Structures, Unions, and Enumerations

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

CS61C Midterm Review on C & Memory Management

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III

CS 5513 Entry Quiz. Systems Programming (CS2213/CS3423))

CSCI 171 Chapter Outlines

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

LOÏC CAPPANERA. 1. Memory management The variables involved in a C program can be stored either statically or dynamically.

Fall 2018 Discussion 2: September 3, 2018

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Memory Organization. The machine code and data associated with it are in the code segment

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

Lesson 7. Reading and Writing a.k.a. Input and Output

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

20 Dynamic allocation of memory: malloc and calloc

Dynamic Allocation of Memory

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

MPATE-GE 2618: C Programming for Music Technology. Unit 5.1

Lecture 3 Memory and Pointers

Recitation #11 Malloc Lab. November 7th, 2017

Lecture 3 Memory and Pointers

2/9/18. Secure Coding. CYSE 411/AIT681 Secure Software Engineering. Agenda. Dynamic Memory Interface. Dynamic Memory Interface

ECE551 Midterm Version 1

Dynamic Allocation in C

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Memory management. Johan Montelius KTH

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS 222: Pointers and Manual Memory Management

CS 110 Computer Architecture. Lecture 4: Introduction to C, Part III. Instructor: Sören Schwertfeger.

Chapter 19 Data Structures -struct -dynamic memory allocation

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.

Transcription:

Memory Management CSC215 Lecture

Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors

Static Allocation Allocation of memory at compile-time before the associated program is executed Let s say we need a list of 1000 names: We can create an array statically char names[1000][20] allocates 20000 bytes at compile time wastes space restricts the size of the names

Dynamic allocation of memory Heap is a chunk of memory that users can use to dynamically allocated memory Lasts until freed, or program exits. Allocate memory during runtime as needed #include <stdlib.h> Use sizeof number to return the number of bytes of a data type. To reserve a specified amount of free memory and returns a void pointer to it, use: malloc calloc Realloc To release a previously allocated memory block, use: free

Dynamic Allocation: malloc C library function allocates the requested memory and returns a pointer to it void *malloc(size_t size) size_t: unsigned integer type size: the size of the requested memory block, in bytes return value: a pointer to the allocated memory, or NULL if the request fails memory block is not cleared (undefined) Example: char *str = (char *) malloc(3*sizeof(char)); *str = 'O'; *(str+1) = 'K'; *(str+2) = '\0';

Dynamic Allocation: realloc C library function attempts to resize the memory block pointed to by a pointer void *realloc(void *ptr, size_t size) ptr: a previously allocated pointer (using malloc, calloc or realloc) if NULL, a new block is allocated malloc size: the total size of the requested memory block, in bytes if 0, the memory pointed to by ptr is freed free return value: a pointer to the allocated memory, or NULL if the request fails may move the memory block to a new location Example: char *str = (char *) malloc( 3 * sizeof(char) ); *str = 'H'; *(str+1) = 'i'; *(str+2) = '\0'; str = (char *) realloc( str, 6 * sizeof(char) ); *(str+1) = 'e'; *(str+2) = 'l'; *(str+3) = 'l'; *(str+4) = 'o'; *(str+5) = '\0'; What is considered a bad practice here?

Dynamic Allocation: calloc Dynamically allocating arrays: allows the user to avoid fixing array size at declaration use malloc to allocate memory for array when needed: int *a = (int *)malloc(sizeof(int)*10); a[0]=1; Alternatively, use: void *calloc(size_t nitems, size_t size) nittems: the number of elements to be allocated size: the size of the requested memory block, in bytes return value: a pointer to the allocated memory, or NULL if the request fails sets allocated memory to 0s Example: int size; char *s; printf( How many characters?\n ); scanf( %d, &size); s = (char *)calloc(size+1, 1); printf( type string\n ); gets(s);

Dynamic Deallocation: free C library function deallocates the memory previously allocated by a call to calloc, malloc, or realloc void free(void *ptr) ptr : the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated If a null pointer is passed as argument, no action occurs. Can only be used on pointers that are dynamically allocated It is an error to free: A pointer that has already been freed Any memory address that has not been directly returned by a dynamic memory allocation routine Example: char *str = (char *)malloc(3*sizeof(char)); /* use str */ free(str);

How It Is Done Best-fit method: an area with m bytes is selected, where m is the smallest available chunk of contiguous memory equal to or larger than n. First-fit method: returns the first chunk encountered containing n or more bytes. Prevention of fragmentation a memory manager may allocate chunks that are larger than the requested size if the space remaining is too small to be useful. When free is called: returns chunks to the available space list as soon as they become free and consolidate adjacent areas

Common Dynamic Allocation Errors Initialization errors do not assume memory returned by malloc and realloc to be filled with zeros Failing to check return values since memory is a limited resource, allocation is not always guaranteed to succeed Memory leak Forgetting to call free when the allocated memory is no more needed Writing to already freed memory if pointer is not set to NULL it is still possible to read/write from where it points to Freeing the same memory multiple times may corrupt data structure Improper use of allocation functions malloc(0): insure non-zero length

Example #include <stdio.h> #include <stdlib.h> int main(){ int input, n, count = 0; int *numbers = NULL, *more_numbers = NULL; do { printf ("Enter an integer (0 to end): "); scanf("%d", &input); count++; more_numbers = (int*)realloc(numbers, count * sizeof(int)); if (more_numbers!=null) { numbers = more_numbers; numbers[count-1]=input; else { free(numbers); puts("error (re)allocating memory"); return 1; while (input!=0); printf ("Numbers entered: "); for (n=0;n<count;n++) printf ("%d ",numbers[n]); free (numbers);

Example: mat.c #include <stdio.h> #include <stdlib.h> #include "mat.h" int** get_matrix(int rows, int cols){ int i, **matrix; if (matrix = (int**)malloc(rows*sizeof(int*))) if (matrix[0] = (int*)calloc(rows*cols,sizeof(int))){ for (i=1; i<rows; i++) matrix[i] = matrix[0] + cols * i; return matrix; return NULL; Compare with: if (matrix = (int**) malloc(rows*sizeof(int*))) for (i=0; i<rows; i++) if(!(matrix[i] = (int*) calloc(cols,sizeof(int)))) return NULL; return matrix; void free_matrix(int** m){ free(m[0]); free(m); Compare with: void free_matrix(int*** m){ free(*m[0]); free(*m); *m = NULL;

Example: mat.c void fill_matrix(int** m, int rows, int cols){ int i, j; for (i=0; i < rows; i++) for (j=0; j < cols; j++){ printf("enter element [%d, %d]:", i, j); scanf("%d", &m[i][j]); void print_matrix(int** m, int rows, int cols){ int i, j; for (i=0; i < rows; i++){ for (j=0; j < cols; j++) printf("%d\t", m[i][j]); printf("\n"); int** transpose(int** m, int rows, int cols){ int i, j, **t = get_matrix(cols, rows); for (i=0; i < rows; i++) for (j=0; j < cols; j++) t[j][i] = m[i][j]; return t;

Example: mat.h #if!defined MAT #define MAT int** get_matrix(int, int); void free_matrix(int**); /* OR */ void free_matrix(int***); void fill_matrix(int**, int, int); void print_matrix(int**, int, int); int** transpose(int**, int, int); #endif

Example: test.c #include <stdio.h> #include "mat.h" int main(){ int r, c; printf("how many rows? "); scanf("%d", &r); printf("how many columns? "); scanf("%d", &c); int** mat = get_matrix(r, c); fill_matrix(mat, r, c); print_matrix(mat, r, c); int** tra = transpose(mat, r, c); print_matrix(tra, c, r); free_matrix(mat); /* OR */ free_matrix(tra); return 0; free_matrix(&mat); free_matrix(&tra);