Jump to content

C dynamic memory allocation

From Wikipedia, the free encyclopedia
(Redirected fromPtmalloc)

C dynamic memory allocationrefers to performingmanual memory managementfordynamic memory allocationin theC programming languagevia a group of functions in theC standard library,namelymalloc,realloc,calloc,aligned_allocandfree.[1][2][3]

TheC++programming language includes these functions; however, the operatorsnewanddeleteprovide similar functionality and are recommended by that language's authors.[4]Still, there are several situations in which usingnew/deleteis not applicable, such as garbage collection code or performance-sensitive code, and a combination ofmallocand placementnewmay be required instead of the higher-levelnewoperator.

Many different implementations of the actual memory allocation mechanism, used bymalloc,are available. Their performance varies in both execution time and required memory.

Rationale

[edit]

TheC programming languagemanages memorystatically,automatically,ordynamically.Static-duration variables are allocated in main memory, usually along with the executable code of the program, and persist for the lifetime of the program; automatic-duration variables are allocated on thestackand come and go as functions are called and return. For static-duration and automatic-duration variables, the size of the allocation must becompile-timeconstant (except for the case of variable-length automatic arrays[5]). If the required size is not known untilrun-time(for example, if data of arbitrary size is being read from the user or from a disk file), then using fixed-size data objects is inadequate.

The lifetime of allocated memory can also cause concern. Neither static- nor automatic-duration memory is adequate for all situations. Automatic-allocated data cannot persist across multiple function calls, while static data persists for the life of the program whether it is needed or not. In many situations the programmer requires greater flexibility in managing the lifetime of allocated memory.

These limitations are avoided by usingdynamic memory allocation,in which memory is more explicitly (but more flexibly) managed, typically by allocating it from thefree store(informally called the "heap" ),[citation needed]an area of memory structured for this purpose. In C, the library functionmallocis used to allocate a block of memory on the heap. The program accesses this block of memory via apointerthatmallocreturns. When the memory is no longer needed, the pointer is passed tofreewhich deallocates the memory so that it can be used for other purposes.

The original description of C indicated thatcallocandcfreewere in the standard library, but notmalloc.Code for a simple model implementation of a storage manager forUnixwas given withallocandfreeas the user interface functions, and using thesbrksystem call to request memory from the operating system.[6]The 6th Edition Unix documentation givesallocandfreeas the low-level memory allocation functions.[7]Themallocandfreeroutines in their modern form are completely described in the 7th Edition Unix manual.[8][9]

Some platforms provide library orintrinsic functioncalls which allow run-time dynamic allocation from the C stack rather than the heap (e.g.alloca()[10]). This memory is automatically freed when the calling function ends.

Overview of functions

[edit]

The C dynamic memory allocation functions are defined instdlib.hheader (cstdlibheader in C++).[1]

Function Description
malloc allocates the specified number of bytes
aligned_alloc allocates the specified number of bytes at the specified alignment
realloc increases or decreases the size of the specified block of memory, moving it if necessary
calloc allocates the specified number of bytes and initializes them to zero
free releases the specified block of memory back to the system

Differences betweenmalloc()andcalloc()

[edit]
  • malloc()takes a single argument (the amount of memory to allocate in bytes), whilecalloc()takes two arguments — the number of elements and the size of each element.
  • malloc()only allocates memory, whilecalloc()allocates and sets the bytes in the allocated region to zero.[11]

Usage example

[edit]

Creating anarrayof ten integers with automatic scope is straightforward in C:

intarray[10];

However, the size of the array is fixed at compile time. If one wishes to allocate a similar array dynamically without using avariable-length array,which is not guaranteed to be supported in allC11implementations, the following code can be used:

int*array=malloc(10*sizeof(int));

This computes the number of bytes that ten integers occupy in memory, then requests that many bytes frommallocand assigns the result to apointernamedarray(due to C syntax, pointers and arrays can be used interchangeably in some situations).

Becausemallocmight not be able to service the request, it might return anull pointerand it isgood programming practiceto check for this:

int*array=malloc(10*sizeof(int));
if(array==NULL){
fprintf(stderr,"malloc failed\n");
return-1;
}

When the program no longer needs thedynamic array,it must eventually callfreeto return the memory it occupies to the free store:

free(array);

The memory set aside bymallocis notinitializedand may containcruft:the remnants of previously used and discarded data. After allocation withmalloc,elements of the array areuninitialized variables.The commandcallocwill return an allocation that has already been cleared:

int*array=calloc(10,sizeof(int));

With realloc we can resize the amount of memory a pointer points to. For example, if we have a pointer acting as an array of sizeand we want to change it to an array of size,we can use realloc.

int*arr=malloc(2*sizeof(int));
arr[0]=1;
arr[1]=2;
arr=realloc(arr,3*sizeof(int));
arr[2]=3;

Note that realloc must be assumed to have changed the base address of the block (i.e. if it has failed to extend the size of the original block, and has therefore allocated a new larger block elsewhere and copied the old contents into it). Therefore, any pointers to addresses within the original block are also no longer valid.

Type safety

[edit]

mallocreturns avoid pointer(void *), which indicates that it is a pointer to a region of unknown data type. The use of casting is required in C++ due to the strong type system, whereas this is not the case in C. One may "cast" (seetype conversion) this pointer to a specific type:

int*ptr,*ptr2;
ptr=malloc(10*sizeof(*ptr));/* without a cast */
ptr2=(int*)malloc(10*sizeof(*ptr));/* with a cast */

There are advantages and disadvantages to performing such a cast.

Advantages to casting

[edit]
  • Including the cast may allow a C program or function to compile as C++.
  • The cast allows forpre-1989 versionsofmallocthat originally returned achar *.[12]
  • Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from themalloc()call (although modern compilers and static analysers can warn on such behaviour without requiring the cast[13]).

Disadvantages to casting

[edit]
  • Under the C standard, the cast is redundant.
  • Adding the cast may mask failure to include the headerstdlib.h,in which thefunction prototypeformallocis found.[12][14]In the absence of a prototype formalloc,the C90 standard requires that the C compiler assumemallocreturns anint.If there is no cast, C90 requires a diagnostic when this integer is assigned to the pointer; however, with the cast, this diagnostic would not be produced, hiding a bug. On certain architectures and data models (such as LP64 on 64-bit systems, wherelongand pointers are 64-bit andintis 32-bit), this error can actually result in undefined behaviour, as the implicitly declaredmallocreturns a 32-bit value whereas the actually defined function returns a 64-bit value. Depending on calling conventions and memory layout, this may result instack smashing.This issue is less likely to go unnoticed in modern compilers, as C99 does not permit implicit declarations, so the compiler must produce a diagnostic even if it does assumeintreturn.
  • If the type of the pointer is changed at its declaration, one may also need to change all lines wheremallocis called and cast.

Common errors

[edit]

The improper use of dynamic memory allocation can frequently be a source of bugs. These can include security bugs or program crashes, most often due tosegmentation faults.

Most common errors are as follows:[15]

Not checking for allocation failures
Memory allocation is not guaranteed to succeed, and may instead return a null pointer. Using the returned value, without checking if the allocation is successful, invokesundefined behavior.This usually leads to crash (due to the resulting segmentation fault on the null pointer dereference), but there is no guarantee that a crash will happen so relying on that can also lead to problems.
Memory leaks
Failure to deallocate memory usingfreeleads to buildup of non-reusable memory, which is no longer used by the program. This wastes memory resources and can lead to allocation failures when these resources are exhausted.
Logical errors
All allocations must follow the same pattern: allocation usingmalloc,usage to store data, deallocation usingfree.Failures to adhere to this pattern, such as memory usage after a call tofree(dangling pointer) or before a call tomalloc(wild pointer), callingfreetwice ( "double free" ), etc., usually causes a segmentation fault and results in a crash of the program. These errors can be transient and hard to debug – for example, freed memory is usually not immediately reclaimed by the OS, and thus dangling pointers may persist for a while and appear to work.

In addition, as an interface that precedes ANSI C standardization,mallocand its associated functions have behaviors that were intentionally left to the implementation to define for themselves. One of them is the zero-length allocation, which is more of a problem withreallocsince it is more common to resize to zero.[16]Although bothPOSIXand theSingle Unix Specificationrequire proper handling of 0-size allocations by either returningNULLor something else that can be safely freed,[17]not all platforms are required to abide by these rules. Among the many double-free errors that it has led to, the 2019WhatsAppRCE was especially prominent.[18]A way to wrap these functions to make them safer is by simply checking for 0-size allocations and turning them into those of size 1. (ReturningNULLhas its own problems: it otherwise indicates an out-of-memory failure. In the case ofreallocit would have signaled that the original memory was not moved and freed, which again is not the case for size 0, leading to the double-free.)[19]

Implementations

[edit]

The implementation of memory management depends greatly upon operating system and architecture. Some operating systems supply an allocator for malloc, while others supply functions to control certain regions of data. The same dynamic memory allocator is often used to implement bothmallocand the operatornewinC++.[20]

Heap-based

[edit]

Implementation of legacy allocators was commonly done using theheap segment.The allocator would usually expand and contract the heap to fulfill allocation requests.

The heap method suffers from a few inherent flaws:

  • A linear allocator can only shrink if the last allocation is released. Even if largely unused, the heap can get "stuck" at a very large size because of a small but long-lived allocation at its tip which could waste any amount of address space, although some allocators on some systems may be able to release entirely empty intermediate pages to the OS.
  • A linear allocator is sensitive tofragmentation,while a good allocator will attempt to track and reuse free slots through the entire heap, as allocation sizes and lifetimes get mixed it can be difficult and expensive to find or coalesce free segments large enough to hold new allocation requests.
  • A linear allocator has extremely poor concurrency characteristics, as the heap segment is per-process every thread has to synchronise on allocation, and concurrent allocations from threads which may have very different work loads amplifies the previous two issues.

dlmalloc and ptmalloc

[edit]

Doug Leahas developed thepublic domaindlmalloc ( "Doug Lea's Malloc" ) as a general-purpose allocator, starting in 1987. TheGNU C library(glibc) is derived from Wolfram Gloger's ptmalloc ( "pthreads malloc" ), a fork of dlmalloc with threading-related improvements.[21][22][23]As of November 2023, the latest version of dlmalloc is version 2.8.6 from August 2012.[24]

dlmalloc is a boundary tag allocator. Memory on theheapis allocated as "chunks", an 8-bytealigneddata structurewhich contains a header, and usable memory. Allocated memory contains an 8- or 16-byte overhead for the size of the chunk and usage flags (similar to adope vector). Unallocated chunks also store pointers to other free chunks in the usable space area, making the minimum chunk size 16 bytes on 32-bit systems and 24/32 (depends on alignment) bytes on 64-bit systems.[22][24]: 2.8.6, Minimum allocated size 

Unallocated memory is grouped into "bins"of similar sizes, implemented by using a double-linked list of chunks (with pointers stored in the unallocated space inside the chunk). Bins are sorted by size into three classes:[22][24]: Overlaid data structures 

  • For requests below 256 bytes (a "smallbin" request), a simple two power best fit allocator is used. If there are no free blocks in that bin, a block from the next highest bin is split in two.
  • For requests of 256 bytes or above but below themmapthreshold, dlmalloc since v2.8.0 usean in-placebitwise triealgorithm( "treebin" ). If there is no free space left to satisfy the request, dlmalloc tries to increase the size of the heap, usually via thebrksystem call. This feature was introduced way after ptmalloc was created (from v2.7.x), and as a result is not a part of glibc, which inherits the old best-fit allocator.
  • For requests above the mmap threshold (a "largebin" request), the memory is always allocated using themmapsystem call. The threshold is usually 128 KB.[25]The mmap method averts problems with huge buffers trapping a small allocation at the end after their expiration, but always allocates an entirepageof memory, which on many architectures is 4096 bytes in size.[26]

Game developer Adrian Stone argues thatdlmalloc,as a boundary-tag allocator, is unfriendly for console systems that have virtual memory but do not havedemand paging.This is because its pool-shrinking and growing callbacks (sysmalloc/systrim) cannot be used to allocate and commit individual pages of virtual memory. In the absence of demand paging, fragmentation becomes a greater concern.[27]

FreeBSD's and NetBSD's jemalloc

[edit]

SinceFreeBSD7.0 andNetBSD5.0, the oldmallocimplementation (phkmallocbyPoul-Henning Kamp) was replaced byjemalloc,written by Jason Evans. The main reason for this was a lack of scalability ofphkmallocin terms of multithreading. In order to avoid lock contention,jemallocuses separate "arenas" for eachCPU.Experiments measuring number of allocations per second in multithreading application have shown that this makes it scale linearly with the number of threads, while for both phkmalloc and dlmalloc performance was inversely proportional to the number of threads.[28]

OpenBSD's malloc

[edit]

OpenBSD's implementation of themallocfunction makes use ofmmap.For requests greater in size than one page, the entire allocation is retrieved usingmmap;smaller sizes are assigned from memory pools maintained bymallocwithin a number of "bucket pages", also allocated withmmap.[29][better source needed]On a call tofree,memory is released and unmapped from the processaddress spaceusingmunmap.This system is designed to improve security by taking advantage of theaddress space layout randomizationand gap page features implemented as part of OpenBSD'smmapsystem call,and to detect use-after-free bugs—as a large memory allocation is completely unmapped after it is freed, further use causes asegmentation faultand termination of the program.

The GrapheneOS project initially started out by porting OpenBSD's memory allocator to Android's Bionic C Library.[30]

Hoard malloc

[edit]

Hoard is an allocator whose goal is scalable memory allocation performance. Like OpenBSD's allocator, Hoard usesmmapexclusively, but manages memory in chunks of 64 kilobytes called superblocks. Hoard's heap is logically divided into a single global heap and a number of per-processor heaps. In addition, there is a thread-local cache that can hold a limited number of superblocks. By allocating only from superblocks on the local per-thread or per-processor heap, and moving mostly-empty superblocks to the global heap so they can be reused by other processors, Hoard keeps fragmentation low while achieving near linear scalability with the number of threads.[31]

mimalloc

[edit]

Anopen-sourcecompact general-purposememory allocatorfromMicrosoft Researchwith focus on performance.[32]The library is about 11,000lines of code.

Thread-caching malloc (tcmalloc)

[edit]

Every thread has athread-local storagefor small allocations. For large allocations mmap orsbrkcan be used.TCMalloc,amallocdeveloped by Google,[33]has garbage-collection for local storage of dead threads. The TCMalloc is considered to be more than twice as fast as glibc's ptmalloc for multithreaded programs.[34][35]

In-kernel

[edit]

Operating systemkernelsneed to allocate memory just as application programs do. The implementation ofmallocwithin a kernel often differs significantly from the implementations used by C libraries, however. For example, memory buffers might need to conform to special restrictions imposed byDMA,or the memory allocation function might be called from interrupt context.[36]This necessitates amallocimplementation tightly integrated with thevirtual memorysubsystem of the operating system kernel.

Overriding malloc

[edit]

Becausemallocand its relatives can have a strong impact on the performance of a program, it is not uncommon to override the functions for a specific application by custom implementations that are optimized for application's allocation patterns. The C standard provides no way of doing this, but operating systems have found various ways to do this by exploiting dynamic linking. One way is to simply link in a different library to override the symbols. Another, employed byUnix System V.3,is to makemallocandfreefunction pointers that an application can reset to custom functions.[37]

The most common form on POSIX-like systems is to set the environment variable LD_PRELOAD with the path of the allocator, so that the dynamic linker uses that version of malloc/calloc/free instead of the libc implementation.

Allocation size limits

[edit]

The largest possible memory blockmalloccan allocate depends on the host system, particularly the size of physical memory and the operating system implementation.

Theoretically, the largest number should be the maximum value that can be held in asize_ttype, which is an implementation-dependent unsigned integer representing the size of an area of memory. In theC99standard and later, it is available as theSIZE_MAXconstant from<stdint.h>.Although not guaranteed byISO C,it is usually2^(CHAR_BIT *sizeof(size_t)) - 1.

On glibc systems, the largest possible memory blockmalloccan allocate is only half this size, namely2^(CHAR_BIT *sizeof(ptrdiff_t) - 1) - 1.[38]

Extensions and alternatives

[edit]

The C library implementations shipping with various operating systems and compilers may come with alternatives and extensions to the standardmallocinterface. Notable among these is:

  • alloca,which allocates a requested number of bytes on thecall stack.No corresponding deallocation function exists, as typically the memory is deallocated as soon as the calling function returns.allocawas present on Unix systems as early as32/V(1978), but its use can be problematic in some (e.g., embedded) contexts.[39]While supported by many compilers, it is not part of theANSI-Cstandard and therefore may not always be portable. It may also cause minor performance problems: it leads to variable-size stack frames, so that bothstack and frame pointersneed to be managed (with fixed-size stack frames, one of these is redundant).[40]Larger allocations may also increase the risk of undefined behavior due to astack overflow.[41]C99 offeredvariable-length arraysas an alternative stack allocation mechanism – however, this feature was relegated to optional in the laterC11standard.
  • POSIXdefines a functionposix_memalignthat allocates memory with caller-specified alignment. Its allocations are deallocated withfree,[42]so the implementation usually needs to be a part of the malloc library.

See also

[edit]

References

[edit]
  1. ^ab7.20.3 Memory management functions(PDF).ISO/IEC 9899:1999 specification(Technical report). p. 313.
  2. ^Summit, Steve."Chapter 11: Memory Allocation".C Programming Notes.Retrieved2020-07-11.
  3. ^"aligned_alloc(3) - Linux man page".
  4. ^Stroustrup, Bjarne(2008).Programming: Principles and Practice Using C++.Addison Wesley. p. 1009.ISBN978-0-321-54372-1.
  5. ^"gcc manual".gnu.org.Retrieved2008-12-14.
  6. ^Brian W. Kernighan, Dennis M. Ritchie,The C Programming Language,Prentice-Hall, 1978; Section 7.9 (page 156) describescallocandcfree,and Section 8.7 (page 173) describes an implementation forallocandfree.
  7. ^alloc(3)Version 6 UnixProgrammer'sManual
  8. ^malloc(3)Version 7 UnixProgrammer'sManual
  9. ^Anonymous,Unix Programmer's Manual, Vol. 1,Holt Rinehart and Winston, 1983 (copyright held by Bell Telephone Laboratories, 1983, 1979); Themanpage formallocetc. is given on page 275.
  10. ^alloca(3)FreeBSDLibrary FunctionsManual
  11. ^calloc(3)LinuxProgrammer'sManual– Library Functions
  12. ^ab"Casting malloc".Cprogramming.com.Retrieved2007-03-09.
  13. ^"clang: lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp Source File".clang.llvm.org.Retrieved2018-04-01.
  14. ^"comp.lang.c FAQ list · Question 7.7b".C-FAQ.Retrieved2007-03-09.
  15. ^Reek, Kenneth (1997-08-04).Pointers on C(1 ed.). Pearson.ISBN9780673999863.
  16. ^"MEM04-C. Beware of zero-length allocations - SEI CERT C Coding Standard - Confluence".wiki.sei.cmu.edu.
  17. ^"POSIX.1-2017: malloc".pubs.opengroup.org.Retrieved2019-11-29.
  18. ^Awakened (2019-10-02)."How a double-free bug in WhatsApp turns to RCE".Retrieved2019-11-29.
  19. ^Felker, Rich [@RichFelker] (2019-10-03)."Wow. The WhatsApp RCE was the wrong behavior for realloc(p,0) so many implementations insist on"(Tweet).Retrieved2022-08-06– viaTwitter.
  20. ^Alexandrescu, Andrei (2001).Modern C++ Design: Generic Programming and Design Patterns Applied.Addison-Wesley. p. 78.
  21. ^"Wolfram Gloger's malloc homepage".malloc.de.Retrieved2018-04-01.
  22. ^abcKaempf, Michel (2001)."Vudo malloc tricks".Phrack(57): 8.Archivedfrom the original on 2009-01-22.Retrieved2009-04-29.
  23. ^"Glibc: Malloc Internals".sourceware.org Trac.Retrieved2019-12-01.
  24. ^abcLee, Doug."A Memory Allocator".Retrieved2019-12-01.HTTP for Source Code
  25. ^"Malloc Tunable Parameters".GNU.Retrieved2009-05-02.
  26. ^Sanderson, Bruce (2004-12-12)."RAM, Virtual Memory, Pagefile and all that stuff".Microsoft Help and Support.
  27. ^Stone, Adrian."The Hole That dlmalloc Can't Fill".Game Angst.Retrieved2019-12-01.
  28. ^Evans, Jason (2006-04-16)."A Scalable Concurrent malloc(3) Implementation for FreeBSD"(PDF).Retrieved2012-03-18.
  29. ^"libc/stdlib/malloc.c".BSD Cross Reference, OpenBSD src/lib/.
  30. ^"History | GrapheneOS".grapheneos.org.Retrieved2023-03-02.
  31. ^Berger, E. D.;McKinley, K. S.;Blumofe, R. D.; Wilson, P. R. (November 2000).Hoard: A Scalable Memory Allocator for Multithreaded Applications(PDF).ASPLOS-IX.Proceedings of the ninth international conference on Architectural support for programming languages and operating systems.pp. 117–128.CiteSeerX10.1.1.1.4174.doi:10.1145/378993.379232.ISBN1-58113-317-0.
  32. ^Microsoft releases optimized malloc() as open source - Slashdot
  33. ^TCMalloc homepage
  34. ^Ghemawat, Sanjay; Menage, Paul;TCMalloc: Thread-Caching Malloc
  35. ^Callaghan, Mark (2009-01-18)."High Availability MySQL: Double sysbench throughput with TCMalloc".Mysqlha.blogspot.com.Retrieved2011-09-18.
  36. ^"kmalloc()/kfree() include/linux/slab.h".People.netfilter.org.Retrieved2011-09-18.
  37. ^Levine, John R.(2000) [October 1999]."Chapter 9: Shared libraries".Linkers and Loaders.The Morgan Kaufmann Series in Software Engineering and Programming (1 ed.). San Francisco, USA:Morgan Kaufmann.ISBN1-55860-496-0.OCLC42413382.Archivedfrom the original on 2012-12-05.Retrieved2020-01-12.Code:[1][2]Errata:[3]
  38. ^"malloc: make malloc fail with requests larger than PTRDIFF_MAX".Sourceware Bugzilla.2019-04-18.Retrieved2020-07-30.
  39. ^"Why is the use of alloca() not considered good practice?".stackoverflow.com.Retrieved2016-01-05.
  40. ^Amarasinghe, Saman; Leiserson, Charles (2010)."6.172 Performance Engineering of Software Systems, Lecture 10".MIT OpenCourseWare.Massachusetts Institute of Technology. Archived fromthe originalon 2015-06-22.Retrieved2015-01-27.
  41. ^"alloca(3) - Linux manual page".man7.org.Retrieved2016-01-05.
  42. ^posix_memalign– System Interfaces Reference,The Single UNIX Specification,Version 4 fromThe Open Group
[edit]