SlideShare a Scribd company logo
1 of 19
Download to read offline
TLPI - Chapter 7 MEMORY ALLOCATION

       Shu-Yu Fu (shuyufu@gmail.com)



               July 15, 2012
TLPI - Chapter 7 MEMORY ALLOCATION




    This chapter describes the functions that are used to allocate
    memory on the heap or the stack.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap




    We begin the a description of brk() (program break, the current
    limit of the heap) and sbrk(), upon which the malloc functions
    are based.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Adjusting the Program Break: brk() and sbrk()


    Resizing the heap is actually as simple as telling the kernel to
    adjust its idea of where the process’s program break is. After
    the program break is increased, the program may access any
    address in the newly allocated area, but no physical memory
    pages are allocated yet.
  1 #include <u n i s t d . h>
  2 i n t brk ( void ∗ e n d d a t a s e g m e n t ) ;
  3 R e t u r n s 0 on s u c c e s s , o r −1 on e r r o r


    The brk() system call sets the program break to the location
    specified by end data segment (page-aligned).
  1 #include <u n i s t d . h>
  2 void ∗ sbrk ( i n t p t r t i n c r e m e n t ) ;
  3 R e t u r n s p r e v i o u s program break on s u c c e s s ,   o r ( void ∗ )−1 on e r r o r


    A call to sbrk() adjusts the program break by adding increment
    to it. On success, sbrk() returns the previous address of the
    program break.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Allocating Memory on the Heap: malloc() and f ree()


  1 #include < s t d l i b . h>
  2 void ∗ m a l l o c ( s i z e t s i z e ) ;
  3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s ,   o r NULL on e r r o r


     The malloc() function allocate size bytes from the heap and
     returns a pointer to the start of the newly allocated block of
     memory.
  1 #include < s t d l i b . h>
  2 void f r e e ( void ∗ p t r ) ;


     In general, f ree() doesn’t lower the program break, but instead
     adds the block of memory to a list of free blocks.
     Making any use of ptr after the call to f ree() is an error that
     can lead to unpredictable results.
            The glibc f ree() function calls sbrk() to lower the
            program break only when the free block at the top end
            is ”sufficiently” large, where ”sufficient” is determined
            by parameters controlling the operation of the malloc
            package (128 KB is a typical value).
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Implementation of malloc() and f ree()


          Scan the list of memory blocks previously released by
          f ree() in order to find one whose size is larger than or
          equal to its requirements.
          If the block is larger, the it is split, so that a block of the
          correct size is returned to the caller and a smaller free
          block is left on the free list.
          If no block on the free list is large enough, malloc()
          increases the program break in larger units, putting the
          excess memory onto the free list.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Implementation of malloc() and f ree()


    Q: When f ree() places a block of memory onto the free list,
    how does it know what size that block is?
    A: When malloc() allocates the block, it allocates extra bytes
    to hold an integer containing the size of the block.




    When a block is placed on the free list, f ree() uses the bytes of
    the block itself in order to add the block to the list.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Tools and libraries for malloc debugging


    Among the malloc debugging tools provided by glibc are the
    following:
         The mtrace() and muntrace() functions allow a program
         to turn tracing of memory allocation calls on and off.
         The mcheck() and mprobe() functions allow a program to
         perform consistency check on blocks of allocated memory.
         Programs that employ these functions must be linked with
         the mcheck library using the −lcheck option.
         The MALLOC CHECK environment variable serves a
         similar purpose to mcheck() and mprobe() (One notable
         difference between the two techniques is that using
         MALLOC CHECK doesn’t require modification and
         recompilation of the program.). For security reasons, the
         setting of MALLOC CHECK is ignored by set-user-ID
         and set-group-ID programs.
    Further information about all of the above features can be
    found in the glibc manual.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Controlling and monitoring the malloc package


    The glibc manual describes a range of nonstandard functions
    (not portable) that can be used to monitor and control the
    allocation of memory by functions in the malloc package.
          The mallopt() function modifies various parameters that
          control the algorithm used by malloc().
          The mallinf o() function returns a structure containing
          various statistics about the memory allocated by malloc().
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Other Methods of Allocating Memory on the Heap


    The C library provides a range of other functions for allocating
    memory on the heap.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Allocating memory with calloc() and realloc()


  1 #include < s t d l i b . h>
  2 void ∗ c a l l o c ( s i z e t numitems , s i z e t s i z e )
  3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s ,   o r NULL on e r r o r


     The calloc() function allocates memory for an array of identical
     items. Unlike malloc(), calloc() initializes the allocated memory
     to 0.
  1 #include < s t d l i b . h>
  2 void ∗ r e a l l o c ( void ∗ p t r , s i z e t s i z e )
  3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s ,   o r NULL on e r r o r


     The realloc() function is used to resize (usually enlarge) a block
     of memory previously allocated by one of the functions in the
     malloc package.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Allocating memory with calloc() and realloc()


    For the usual case, where we are increasing the size of the block
    of memory,
          realloc() attempts to coalesce the block with an
          immediately following block of memory on the free list, if
          one exists and is large enough.
          If the block lies at the end of the heap, then realloc()
          expands the heap.
          If the block of memory lies in the middle of the heap, and
          there is insufficient free space immediately following it,
          realloc() allocates a new block of memory and copies all
          existing data from the old block to the new block.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Allocating memory with calloc() and realloc()


     Since realloc() may relocate the block of memory, we must use
     the returned pointer from realloc() for future references to the
     memory block.
  1 nptr = r e a l l o c ( ptr , newsize ) ;
  2 i f ( n p t r == NULL) {
  3    /∗ H a n d l e e r r o r ∗/
  4 } e l s e { /∗ r e a l l o c ( ) s u c c e e d e d ∗/
  5    ptr = nptr ;
  6 }


     Memory allocated using calloc() or realloc() should be
     deallocated with f ree().
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Allocating aligned memory: memalign() and posix memalign()


  1 #include <m a l l o c . h>
  2 void ∗ memalign ( s i z e t boundary , s i z e t s i z e ) ;
  3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s ,   o r NULL on e r r o r


     The memalign() function allocates size bytes starting at an
     address aligned to a multiple of boundary, which must be a
     power of two.
  1 #include < s t d l i b . h>
  2 i n t p o s i x m e m a l i g n ( void ∗∗memptr , s i z e t a l i g n m e n t , s i z e t   size ) ;
  3 R e t u r n s 0 on s u c c e s s , o r a p o s i t i v e e r r o r number on e r r o r


     The memory is aligned to a multiple of alignment, which must
     be a power-of-two multiple of sizeof (void∗) (4 or 8 bytes on
     most hardware architectures). Note also the unusual return
     value of this function.
     Blocks of memory allocated using memalign() or
     posix memalign() should be deallocated with f ree().
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Heap
   Allocating aligned memory: memalign() and posix memalign()


          On some UNIX implementations, it is not possible to
          call f ree() on a block of memory allocated via
          memalign(), because the memalign() implementation
          uses malloc() to allocate a block of memory, and then
          returns a pointer to an address with a suitable
          alignment in that block. The glibc implementation of
          memalign() doesn’t suffer this limitation.
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Stack: alloca()




    Instead of obtaining memory from the heap, alloca() obtains
    memory from the stack by increasing the size of the stack frame.
  1 #include <a l l o c a >
  2 void ∗ a l l o c a ( s i z e t s i z e ) ;
  3 Returns p o i n t e r to a l l o c a t e d   block   o f memory


    We need no call f ree() to deallocate memory allocated with
    alloca(). Likewise, it is not possible to use realloc() to resize a
    block of memory allocated by alloca().
            Older versions of glibc, and some other UNIX
            implementations (mainly BSD derivatives), require the
            inclusion of <stdlib.h> instead of <alloca.h> to obtain
            the declaration of alloca().
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Stack: alloca()



    If the stack overflow as a consequence of calling alloca(), the
    program behavior is unpredictable. In particular, we don’t get a
    NULL return to inform us of the error. (In fact, in this
    circumstance, we may receive a SIGSEGV signal.)
    We can’t use alloca() within a function argument list, as in this
    example:
  1 func (x ,   a l l o c a ( s i z e ) , z ) ; /∗ WRONG! ∗/


    Instead, we must use code such as this:
  1 void ∗y ;
  2 y = alloca ( size ) ;
  3 func (x , y , z ) ;
TLPI - Chapter 7 MEMORY ALLOCATION
 Allocating Memory on the Stack: alloca()



    Using alloca() to allocate memory has a few advantages over
    malloc().
          alloca() is faster than malloc().
          The memory that alloca() allocates is automatically freed
          when the stack frame is removed.
    Using alloca() can be especially useful if we employ longjmp()
    or siglongjmp() to perform a nonlocal goto from a signal
    handler.
TLPI - Chapter 7 MEMORY ALLOCATION
 Summary




           Using the malloc family of functions, a process can
           dynamically allocate and release memory on the heap.
           The alloca() function allocates memory on the stack.

More Related Content

What's hot

Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Kamal Acharya
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocationRohit Shrivastava
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in clavanya marichamy
 
Dma
DmaDma
DmaAcad
 
Malloc() and calloc() in c
Malloc() and calloc() in cMalloc() and calloc() in c
Malloc() and calloc() in cMahesh Tibrewal
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocationvaani pathak
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocationGrishma Rajput
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation웅식 전
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessIgor Sfiligoi
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Ganesan Narayanasamy
 
deep learning library coyoteの開発(CNN編)
deep learning library coyoteの開発(CNN編)deep learning library coyoteの開発(CNN編)
deep learning library coyoteの開発(CNN編)Kotaro Tanahashi
 
Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*Intel® Software
 

What's hot (20)

Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocation
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Dma
DmaDma
Dma
 
Malloc() and calloc() in c
Malloc() and calloc() in cMalloc() and calloc() in c
Malloc() and calloc() in c
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Stack and heap
Stack and heapStack and heap
Stack and heap
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
 
Survey onhpcs languages
Survey onhpcs languagesSurvey onhpcs languages
Survey onhpcs languages
 
Pointer
PointerPointer
Pointer
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117
 
deep learning library coyoteの開発(CNN編)
deep learning library coyoteの開発(CNN編)deep learning library coyoteの開発(CNN編)
deep learning library coyoteの開発(CNN編)
 
Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*
 

Viewers also liked

程式設計師的自我修養 Chapter 3.4
程式設計師的自我修養 Chapter 3.4程式設計師的自我修養 Chapter 3.4
程式設計師的自我修養 Chapter 3.4Shu-Yu Fu
 
Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductionsirshad17
 
程式設計師的自我修養 Chapter 5
程式設計師的自我修養 Chapter 5程式設計師的自我修養 Chapter 5
程式設計師的自我修養 Chapter 5Shu-Yu Fu
 
TLPI - Chapter 44 Pipe and Fifos
TLPI - Chapter 44 Pipe and FifosTLPI - Chapter 44 Pipe and Fifos
TLPI - Chapter 44 Pipe and FifosShu-Yu Fu
 
程式設計師的自我修養 Chapter 1
程式設計師的自我修養 Chapter 1程式設計師的自我修養 Chapter 1
程式設計師的自我修養 Chapter 1Shu-Yu Fu
 
程式設計師的自我修養 Chapter 10 記憶體
程式設計師的自我修養 Chapter 10 記憶體程式設計師的自我修養 Chapter 10 記憶體
程式設計師的自我修養 Chapter 10 記憶體Shu-Yu Fu
 
程式設計師的自我修養 Chapter 8
程式設計師的自我修養 Chapter 8程式設計師的自我修養 Chapter 8
程式設計師的自我修養 Chapter 8Shu-Yu Fu
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in cPrabhu Govind
 
Memory allocation for real time operating system
Memory allocation for real time operating systemMemory allocation for real time operating system
Memory allocation for real time operating systemAsma'a Lafi
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Viewers also liked (10)

程式設計師的自我修養 Chapter 3.4
程式設計師的自我修養 Chapter 3.4程式設計師的自我修養 Chapter 3.4
程式設計師的自我修養 Chapter 3.4
 
Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductions
 
程式設計師的自我修養 Chapter 5
程式設計師的自我修養 Chapter 5程式設計師的自我修養 Chapter 5
程式設計師的自我修養 Chapter 5
 
TLPI - Chapter 44 Pipe and Fifos
TLPI - Chapter 44 Pipe and FifosTLPI - Chapter 44 Pipe and Fifos
TLPI - Chapter 44 Pipe and Fifos
 
程式設計師的自我修養 Chapter 1
程式設計師的自我修養 Chapter 1程式設計師的自我修養 Chapter 1
程式設計師的自我修養 Chapter 1
 
程式設計師的自我修養 Chapter 10 記憶體
程式設計師的自我修養 Chapter 10 記憶體程式設計師的自我修養 Chapter 10 記憶體
程式設計師的自我修養 Chapter 10 記憶體
 
程式設計師的自我修養 Chapter 8
程式設計師的自我修養 Chapter 8程式設計師的自我修養 Chapter 8
程式設計師的自我修養 Chapter 8
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Memory allocation for real time operating system
Memory allocation for real time operating systemMemory allocation for real time operating system
Memory allocation for real time operating system
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar to TLPI - 7 Memory Allocation

Similar to TLPI - 7 Memory Allocation (20)

Tips of Malloc & Free
Tips of Malloc & FreeTips of Malloc & Free
Tips of Malloc & Free
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Dma
DmaDma
Dma
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
Understanding SLAB in Linux Kernel
Understanding SLAB in Linux KernelUnderstanding SLAB in Linux Kernel
Understanding SLAB in Linux Kernel
 
dynamicmemoryallocation.pptx
dynamicmemoryallocation.pptxdynamicmemoryallocation.pptx
dynamicmemoryallocation.pptx
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Smashing the stack for fun and profit
Smashing the stack for fun and profitSmashing the stack for fun and profit
Smashing the stack for fun and profit
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
C interview questions
C interview questionsC interview questions
C interview questions
 
Buffer overflow attack
Buffer overflow attackBuffer overflow attack
Buffer overflow attack
 
Low Level Exploits
Low Level ExploitsLow Level Exploits
Low Level Exploits
 
Scope Stack Allocation
Scope Stack AllocationScope Stack Allocation
Scope Stack Allocation
 
Memory manament in C
Memory manament in CMemory manament in C
Memory manament in C
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
 
final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Memory model
Memory modelMemory model
Memory model
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 

More from Shu-Yu Fu

Tlpi chapter 38 writing secure privileged programs
Tlpi   chapter 38 writing secure privileged programsTlpi   chapter 38 writing secure privileged programs
Tlpi chapter 38 writing secure privileged programsShu-Yu Fu
 
TLPI Chapter 14 File Systems
TLPI Chapter 14 File SystemsTLPI Chapter 14 File Systems
TLPI Chapter 14 File SystemsShu-Yu Fu
 
團隊之美 第三篇 實踐 (Part 1)
團隊之美 第三篇 實踐 (Part 1)團隊之美 第三篇 實踐 (Part 1)
團隊之美 第三篇 實踐 (Part 1)Shu-Yu Fu
 
團隊之美 第二篇 目標
團隊之美 第二篇 目標團隊之美 第二篇 目標
團隊之美 第二篇 目標Shu-Yu Fu
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 ProcessShu-Yu Fu
 
大家來學GObject
大家來學GObject大家來學GObject
大家來學GObjectShu-Yu Fu
 

More from Shu-Yu Fu (6)

Tlpi chapter 38 writing secure privileged programs
Tlpi   chapter 38 writing secure privileged programsTlpi   chapter 38 writing secure privileged programs
Tlpi chapter 38 writing secure privileged programs
 
TLPI Chapter 14 File Systems
TLPI Chapter 14 File SystemsTLPI Chapter 14 File Systems
TLPI Chapter 14 File Systems
 
團隊之美 第三篇 實踐 (Part 1)
團隊之美 第三篇 實踐 (Part 1)團隊之美 第三篇 實踐 (Part 1)
團隊之美 第三篇 實踐 (Part 1)
 
團隊之美 第二篇 目標
團隊之美 第二篇 目標團隊之美 第二篇 目標
團隊之美 第二篇 目標
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
 
大家來學GObject
大家來學GObject大家來學GObject
大家來學GObject
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

TLPI - 7 Memory Allocation

  • 1. TLPI - Chapter 7 MEMORY ALLOCATION Shu-Yu Fu (shuyufu@gmail.com) July 15, 2012
  • 2. TLPI - Chapter 7 MEMORY ALLOCATION This chapter describes the functions that are used to allocate memory on the heap or the stack.
  • 3. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap We begin the a description of brk() (program break, the current limit of the heap) and sbrk(), upon which the malloc functions are based.
  • 4. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Adjusting the Program Break: brk() and sbrk() Resizing the heap is actually as simple as telling the kernel to adjust its idea of where the process’s program break is. After the program break is increased, the program may access any address in the newly allocated area, but no physical memory pages are allocated yet. 1 #include <u n i s t d . h> 2 i n t brk ( void ∗ e n d d a t a s e g m e n t ) ; 3 R e t u r n s 0 on s u c c e s s , o r −1 on e r r o r The brk() system call sets the program break to the location specified by end data segment (page-aligned). 1 #include <u n i s t d . h> 2 void ∗ sbrk ( i n t p t r t i n c r e m e n t ) ; 3 R e t u r n s p r e v i o u s program break on s u c c e s s , o r ( void ∗ )−1 on e r r o r A call to sbrk() adjusts the program break by adding increment to it. On success, sbrk() returns the previous address of the program break.
  • 5. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Allocating Memory on the Heap: malloc() and f ree() 1 #include < s t d l i b . h> 2 void ∗ m a l l o c ( s i z e t s i z e ) ; 3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s , o r NULL on e r r o r The malloc() function allocate size bytes from the heap and returns a pointer to the start of the newly allocated block of memory. 1 #include < s t d l i b . h> 2 void f r e e ( void ∗ p t r ) ; In general, f ree() doesn’t lower the program break, but instead adds the block of memory to a list of free blocks. Making any use of ptr after the call to f ree() is an error that can lead to unpredictable results. The glibc f ree() function calls sbrk() to lower the program break only when the free block at the top end is ”sufficiently” large, where ”sufficient” is determined by parameters controlling the operation of the malloc package (128 KB is a typical value).
  • 6. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Implementation of malloc() and f ree() Scan the list of memory blocks previously released by f ree() in order to find one whose size is larger than or equal to its requirements. If the block is larger, the it is split, so that a block of the correct size is returned to the caller and a smaller free block is left on the free list. If no block on the free list is large enough, malloc() increases the program break in larger units, putting the excess memory onto the free list.
  • 7. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Implementation of malloc() and f ree() Q: When f ree() places a block of memory onto the free list, how does it know what size that block is? A: When malloc() allocates the block, it allocates extra bytes to hold an integer containing the size of the block. When a block is placed on the free list, f ree() uses the bytes of the block itself in order to add the block to the list.
  • 8. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Tools and libraries for malloc debugging Among the malloc debugging tools provided by glibc are the following: The mtrace() and muntrace() functions allow a program to turn tracing of memory allocation calls on and off. The mcheck() and mprobe() functions allow a program to perform consistency check on blocks of allocated memory. Programs that employ these functions must be linked with the mcheck library using the −lcheck option. The MALLOC CHECK environment variable serves a similar purpose to mcheck() and mprobe() (One notable difference between the two techniques is that using MALLOC CHECK doesn’t require modification and recompilation of the program.). For security reasons, the setting of MALLOC CHECK is ignored by set-user-ID and set-group-ID programs. Further information about all of the above features can be found in the glibc manual.
  • 9. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Controlling and monitoring the malloc package The glibc manual describes a range of nonstandard functions (not portable) that can be used to monitor and control the allocation of memory by functions in the malloc package. The mallopt() function modifies various parameters that control the algorithm used by malloc(). The mallinf o() function returns a structure containing various statistics about the memory allocated by malloc().
  • 10. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Other Methods of Allocating Memory on the Heap The C library provides a range of other functions for allocating memory on the heap.
  • 11. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Allocating memory with calloc() and realloc() 1 #include < s t d l i b . h> 2 void ∗ c a l l o c ( s i z e t numitems , s i z e t s i z e ) 3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s , o r NULL on e r r o r The calloc() function allocates memory for an array of identical items. Unlike malloc(), calloc() initializes the allocated memory to 0. 1 #include < s t d l i b . h> 2 void ∗ r e a l l o c ( void ∗ p t r , s i z e t s i z e ) 3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s , o r NULL on e r r o r The realloc() function is used to resize (usually enlarge) a block of memory previously allocated by one of the functions in the malloc package.
  • 12. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Allocating memory with calloc() and realloc() For the usual case, where we are increasing the size of the block of memory, realloc() attempts to coalesce the block with an immediately following block of memory on the free list, if one exists and is large enough. If the block lies at the end of the heap, then realloc() expands the heap. If the block of memory lies in the middle of the heap, and there is insufficient free space immediately following it, realloc() allocates a new block of memory and copies all existing data from the old block to the new block.
  • 13. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Allocating memory with calloc() and realloc() Since realloc() may relocate the block of memory, we must use the returned pointer from realloc() for future references to the memory block. 1 nptr = r e a l l o c ( ptr , newsize ) ; 2 i f ( n p t r == NULL) { 3 /∗ H a n d l e e r r o r ∗/ 4 } e l s e { /∗ r e a l l o c ( ) s u c c e e d e d ∗/ 5 ptr = nptr ; 6 } Memory allocated using calloc() or realloc() should be deallocated with f ree().
  • 14. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Allocating aligned memory: memalign() and posix memalign() 1 #include <m a l l o c . h> 2 void ∗ memalign ( s i z e t boundary , s i z e t s i z e ) ; 3 R e t u r n s p o i n t e r t o a l l o c a t e d memory on s u c c e s s , o r NULL on e r r o r The memalign() function allocates size bytes starting at an address aligned to a multiple of boundary, which must be a power of two. 1 #include < s t d l i b . h> 2 i n t p o s i x m e m a l i g n ( void ∗∗memptr , s i z e t a l i g n m e n t , s i z e t size ) ; 3 R e t u r n s 0 on s u c c e s s , o r a p o s i t i v e e r r o r number on e r r o r The memory is aligned to a multiple of alignment, which must be a power-of-two multiple of sizeof (void∗) (4 or 8 bytes on most hardware architectures). Note also the unusual return value of this function. Blocks of memory allocated using memalign() or posix memalign() should be deallocated with f ree().
  • 15. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Heap Allocating aligned memory: memalign() and posix memalign() On some UNIX implementations, it is not possible to call f ree() on a block of memory allocated via memalign(), because the memalign() implementation uses malloc() to allocate a block of memory, and then returns a pointer to an address with a suitable alignment in that block. The glibc implementation of memalign() doesn’t suffer this limitation.
  • 16. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Stack: alloca() Instead of obtaining memory from the heap, alloca() obtains memory from the stack by increasing the size of the stack frame. 1 #include <a l l o c a > 2 void ∗ a l l o c a ( s i z e t s i z e ) ; 3 Returns p o i n t e r to a l l o c a t e d block o f memory We need no call f ree() to deallocate memory allocated with alloca(). Likewise, it is not possible to use realloc() to resize a block of memory allocated by alloca(). Older versions of glibc, and some other UNIX implementations (mainly BSD derivatives), require the inclusion of <stdlib.h> instead of <alloca.h> to obtain the declaration of alloca().
  • 17. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Stack: alloca() If the stack overflow as a consequence of calling alloca(), the program behavior is unpredictable. In particular, we don’t get a NULL return to inform us of the error. (In fact, in this circumstance, we may receive a SIGSEGV signal.) We can’t use alloca() within a function argument list, as in this example: 1 func (x , a l l o c a ( s i z e ) , z ) ; /∗ WRONG! ∗/ Instead, we must use code such as this: 1 void ∗y ; 2 y = alloca ( size ) ; 3 func (x , y , z ) ;
  • 18. TLPI - Chapter 7 MEMORY ALLOCATION Allocating Memory on the Stack: alloca() Using alloca() to allocate memory has a few advantages over malloc(). alloca() is faster than malloc(). The memory that alloca() allocates is automatically freed when the stack frame is removed. Using alloca() can be especially useful if we employ longjmp() or siglongjmp() to perform a nonlocal goto from a signal handler.
  • 19. TLPI - Chapter 7 MEMORY ALLOCATION Summary Using the malloc family of functions, a process can dynamically allocate and release memory on the heap. The alloca() function allocates memory on the stack.