Memory (Stack and Heap)

Similar documents
Lecture 8 Dynamic Memory Allocation

Memory Management. CS449 Fall 2017

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

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

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

C Praktikum. Advanced Pointers. Eugen Betke, Nathanael Hübbe, Michael Kuhn, Jakob Lüttgau, Jannek Squar

Dynamic memory allocation (malloc)

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

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Memory Management. CSC215 Lecture

Dynamic Memory. R. Inkulu (Dynamic Memory) 1 / 19

Understanding Pointers

CSC 1600 Memory Layout for Unix Processes"

Introduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th

Heap Arrays. Steven R. Bagley

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

Memory Allocation. General Questions

C Structures & Dynamic Memory Management

Dynamic Allocation of Memory

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

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

TI2725-C, C programming lab, course

Dynamic memory allocation

Dynamic Memory Allocation I Nov 5, 2002

CS 11 C track: lecture 5

C PROGRAMMING Lecture 5. 1st semester

Dynamic Memory Management

Quick review pointer basics (KR ch )

Dynamic Memory Allocation I

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

Arrays and Memory Management

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

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation

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

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

Dynamic Memory Allocation

Processes. Johan Montelius KTH

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

A process. the stack

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

Dynamic Data Structures. CSCI 112: Programming in C

Class Information ANNOUCEMENTS

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

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

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

Heap Arrays and Linked Lists. Steven R. Bagley

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Operating System Labs. Yuanbin Wu

Dynamically Allocated Memory in C

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Dynamic Memory Allocation: Basic Concepts

Limitations of the stack

Dynamic Allocation in C

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

CSC209H Lecture 3. Dan Zingaro. January 21, 2015


Dynamic Memory Allocation

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

POINTER AND ARRAY SUNU WIBIRAMA

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Secure Coding in C and C++

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

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

Hacking in C. Memory layout. Radboud University, Nijmegen, The Netherlands. Spring 2018

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

DAY 3. CS3600, Northeastern University. Alan Mislove

Systems Programming and Computer Architecture ( )

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

Agenda. Dynamic Memory Management. Robert C. Seacord. Secure Coding in C and C++

CS24 Week 2 Lecture 1

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

Content. In this chapter, you will learn:

The Environment of a Unix Process

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

Scientific Programming in C IV. Pointers

Dynamic Memory Allocation. Gerson Robboy Portland State University. class20.ppt

Secure Software Programming and Vulnerability Analysis

14. Memory API. Operating System: Three Easy Pieces

COSC Software Engineering. Lecture 16: Managing Memory Managers

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

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

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package

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

Dynamic Allocation in C

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

CA341 - Comparative Programming Languages

Pointers, Arrays, Memory: AKA the cause of those Segfaults

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

Memory management. Johan Montelius KTH

Advanced practical Programming for Scientists

Dynamic Memory & ADTs in C. The heap. Readings: CP:AMA 17.1, 17.2, 17.3, The primary goal of this section is to be able to use dynamic memory.

Dynamic Memory & ADTs in C

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Kurt Schmidt. October 30, 2018

Dynamic memory. EECS 211 Winter 2019

CSCI 171 Chapter Outlines

Memory Allocation in C

Transcription:

Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03 Eugen Betke Memory (Stack and Heap) 1 / 27

1 Introduction 2 Heap vs. Stack 3 Memory management in C Library Common techniques 4 Pitfalls 5 Quellen Eugen Betke Memory (Stack and Heap) 2 / 27

Virtual address space Modern operating systems manage memory allocation A page table maps physical memory to virtual address space Each process see contiguous memory space Eugen Betke Memory (Stack and Heap) 3 / 27

Memory layout of C programs Abbildung: Memory Layout [1] Text segment Contains executable instructions Often read only and shared by processes DATA: Data segment, initialized by programmer BSS: Data segment, uninitialized by programmer Initialized to arithmetic 0 Stores global and static variables Stack Stores automatic variables Typically grows from higher addresses towards zero Heap Dynamically allocated space Begins at the end of BSS segment Eugen Betke Memory (Stack and Heap) 4 / 27

1 Introduction 2 Heap vs. Stack 3 Memory management in C Library Common techniques 4 Pitfalls 5 Quellen Eugen Betke Memory (Stack and Heap) 5 / 27

Stack vs. Heap [2] Stack very fast access don t have to explicitly de-allocate variables space is managed efficiently by CPU, memory will not become fragmented local variables only limit on stack size (OS-dependent) variables cannot be resized Heap variables can be accessed globally no limit on memory size (relatively) slower access no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed you must manage memory (you re in charge of allocating and freeing variables) variables can be resized using realloc() Eugen Betke Memory (Stack and Heap) 6 / 27

1 Introduction 2 Heap vs. Stack 3 Memory management in C Library Common techniques 4 Pitfalls 5 Quellen Eugen Betke Memory (Stack and Heap) 7 / 27

Library C memory management functions malloc calloc realloc free allocates memory allocates and zeroes memory expands previously allocated memory block deallocates previously allocated memory The memory management functions allocate and deallocated memory on the heap are defined in header <stdlib.h> Eugen Betke Memory (Stack and Heap) 8 / 27

Library malloc 1 void *malloc(size_t size); Allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free(). Eugen Betke Memory (Stack and Heap) 9 / 27

Library calloc 1 void *calloc(size_t nmemb, size_t size); Allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory The memory is set to zero If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free() Eugen Betke Memory (Stack and Heap) 10 / 27

Library realloc 1 void *realloc(void *ptr, size_t size); Changes the size of the memory block pointed to by ptr to size bytes The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. 1 p = realloc(null, size); 2 // the same as 3 p = malloc(size); 1 realloc(ptr, 0); 2 // the same as 3 free(ptr) Eugen Betke Memory (Stack and Heap) 11 / 27

Library free 1 void free(void *ptr); Frees the memory space pointed to by ptr ptr must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. Eugen Betke Memory (Stack and Heap) 12 / 27

Library Usage example 1 /* Allocate space for an array with ten elements of type int. */ 2 int *ptr = (int *) malloc(10 * sizeof (int)); 3 if (ptr == NULL) { 4 /* Memory could not be allocated, the program should 5 handle the error here as appropriate. */ 6 } else { 7 /* Allocation succeeded. Do something. */ 8 free(ptr); 9 ptr = NULL; 10 } Eugen Betke Memory (Stack and Heap) 13 / 27

Library Allocation idiom 1 int *ptr1 = malloc(10 * sizeof(int)); Listing 1: Straight forward allocation 1 int *ptr2 = malloc(10 * sizeof(*ptr)); Listing 2: Allocation idiom Insted of sizeof(int) we used sizeof(*ptr) sizeof() automatically determines the correct size of *ptr If type changes, the malloc still provides right amount of memory Eugen Betke Memory (Stack and Heap) 14 / 27

Common techniques Single dynamic allocation with ownership semantics 1 { 2 struct obj otmp; 3 /* do stuff with otmp */ 4 } 5 6 { 7 struct obj *otmp; 8 otmp = malloc(sizeof *otmp); 9 /* do stuff with otmp */ 10 free(otmp); 11 } User is responsible for memory allocation and deallocation Memory is allocated and released in the same scope Eugen Betke Memory (Stack and Heap) 15 / 27

Common techniques Dynamic memory allocation in functions 1 int *my_func(void) { 2 int * x; 3 x = (int *) malloc(25); 4 return x; 5 } 6 7 int main(int argc, char** argv) { 8 int *pi = my_func(); 9 /* do something with pi */ 10 free(pi); 11 return 0; 12 } Memory is allocated by malloc in a function The user is responsible for deallocation Eugen Betke Memory (Stack and Heap) 16 / 27

1 Introduction 2 Heap vs. Stack 3 Memory management in C Library Common techniques 4 Pitfalls 5 Quellen Eugen Betke Memory (Stack and Heap) 17 / 27

Common pitfalls Memory management is a source for bugs [4], e.g. Memory leaks Use after free Freeing not dynamically allocated memory Accessing not allocated memory Multiple free Eugen Betke Memory (Stack and Heap) 18 / 27

Memory leaks 1 int memory_leak() { 2 int* ptr = malloc(sizeof(*ptr)); 3 return 0; 4 } Pointer get lost after function returns Memory stays allocated, until program exits Eugen Betke Memory (Stack and Heap) 19 / 27

Use after free 1 int *ptr = malloc(sizeof (int)); 2 free(ptr); 3 *ptr = 7; /* Undefined behavior */ Memory is used after it was freed Results in undefined behaviour Eugen Betke Memory (Stack and Heap) 20 / 27

Freeing not dynamically allocated memory 1 char *msg = "Default message"; 2 int tbl[100]; 3 free(msg); 4 free(tbl); Freeing memory that was not allocated by malloc, calloc or realloc Results in undefined behaviour Eugen Betke Memory (Stack and Heap) 21 / 27

Accessing not allocated memory 1 int *my_func(void) { 2 int x[25]; 3 return x; 4 } 5 6 int main(int argc, char** argv) { 7 int *pi = my_func(); 8 *(pi + 1) = 5; 9 free(pi); 10 return 0; 11 } Not allocated memory is used after freed Eugen Betke Memory (Stack and Heap) 22 / 27

Multiple free 1 void main(){ 2 int *p; 3 p = (int *)malloc(10 * sizeof(int)); 4 f(p); 5 free(p); 6 } 7 void f(int *g){ 8 printf("%d", g); 9 free(g); 10 } The same allocation is freed several times Results in undefined behaviour Eugen Betke Memory (Stack and Heap) 23 / 27

Summary From application s perspective, memory is a contigous space partitioned in segments (Text, DATA, BSS, Stack and Heap) Memory management On stack memory is managed for you On heap the user is responsible for memory management Memory management functions are defined in <stdlib.h> Common bugs Memory leaks Use after free Freeing not dynamically allocated memory Accessing not allocated memory Multiple free Eugen Betke Memory (Stack and Heap) 24 / 27

1 Introduction 2 Heap vs. Stack 3 Memory management in C Library Common techniques 4 Pitfalls 5 Quellen Eugen Betke Memory (Stack and Heap) 25 / 27

Quellen I [1] GeeksforGeeks. Memory Layout of C Programs. https://www.geeksforgeeks.org/memory-layout-of-c-program/. Accessed on 03.12.2014. [2] Gribblelab. Memory: Stack vs Heap. https: //www.gribblelab.org/cbootcamp/7_memory_stack_vs_heap.html. Accessed on 03.12.2014. [3] Turkeyland. Buffer Overflows and You. https://turkeyland.net/projects/overflow/intro.php. Accessed on 03.12.2014. Eugen Betke Memory (Stack and Heap) 26 / 27

Quellen II [4] Wikibooks. C Programming/stdlib.h/malloc. https: //en.wikibooks.org/wiki/c_programming/stdlib.h/malloc. Accessed on 03.12.2014. Eugen Betke Memory (Stack and Heap) 27 / 27