FACTOID # 17: Though Rhode Island is the smallest state in total area, it has the longest official name: The State of Rhode Island and Providence Plantations.
 
 Home   Encyclopedia   Statistics   States A-Z   Flags   Maps   FAQ   About 
   
 
WHAT'S NEW
RELATED ARTICLES
People who viewed "Malloc" also viewed:
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Malloc

In computing, malloc is a subroutine provided in the C programming language's and C++ programming language's standard library for performing dynamic memory allocation. RAM (Random Access Memory) Look up computing in Wiktionary, the free dictionary. ... In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and can be relatively independent of the remaining code. ... C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose programming language with high-level and low-level capabilities. ... In C++, the Standard Library is a collection of classes and functions, which are written in the core language. ... In computer science, dynamic memory allocation is the allocation of memory storage for use in a computer program during the runtime of that program. ...

Contents

Rationale

The C programming language manages memory either statically or automatically. Static-duration variables are allocated in main (fixed) memory and persist for the lifetime of the program; automatic-duration variables are allocated on the stack and come and go as functions are called and return. For static-duration and, until C99 which allows variable-sized arrays, automatic-duration variables, the size of the allocation must be a compile-time constant. If the required size will not be known until run-time — for example, if data of arbitrary size is being read from the user or from a disk file — using fixed-size data objects is inadequate. Some platforms provide the alloca function,[1] which allows run-time allocation of variable-sized automatic variables on the stack. Wikibooks has a book on the topic of C Programming The C programming language (often, just C) is a general-purpose, procedural, imperative computer programming language developed in the early 1970s by Dennis Ritchie for use on the Unix operating system. ... A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... To meet Wikipedias quality standards, this article or section may require cleanup. ... Static memory allocation refers to the process of allocating memory at compile-time before the associated program is executed, unlike dynamic memory allocation or automatic memory allocation where memory is allocated as required at run-time. ... It has been suggested that this article or section be merged with Function stack. ... In computer science, a call stack is a special stack which stores information about the active subroutines of a computer program. ... The C Programming Language, Brian Kernighan and Dennis Ritchie, the original edition that served for many years as an informal specification of the language The C programming language is a low_level standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX... In computer science, compile time, as opposed to runtime, is the time when a compiler compiles code written in a programming language into an executable form. ... In computer science, runtime describes the operation of a computer program, the duration of its execution, from beginning to termination (compare compile time). ...


The lifetime of allocated memory is also a concern. Neither static- nor automatic-duration memory is adequate for all situations. Stack-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 using dynamic memory allocation in which memory is more explicitly but more flexibly managed, typically by allocating it from a heap, an area of memory structured for this purpose. In C, one uses the library function malloc to allocate a block of memory on the heap. The program accesses this block of memory via a pointer which malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes. In computer science, dynamic memory allocation is the allocation of memory storage for use in a computer program during the runtime of that program. ... In computer science, dynamic memory allocation is the allocation of memory storage for use in a computer program during the runtime of that program. ... It has been suggested that Software pointer be merged into this article or section. ...


Dynamic memory allocation in C

The malloc function is the basic function used to allocate memory on the heap in C. Its function prototype is A function prototype in C or C++ is a declaration of a function that omits the function body but does specify the functions name, arity, argument types and return type. ...

 void *malloc(size_t size); 

which allocates size bytes of memory. If the allocation succeeds, a pointer to the block of memory is returned.


malloc returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. Note that because malloc returns a void pointer, it needn't be explicitly cast to a more specific pointer type: ANSI C defines an implicit coercion between the void pointer type and other pointer types. An explicit cast of malloc's return value is sometimes performed because malloc originally returned a char *, but this cast is unnecessary in modern C code.[2][3] Omitting the cast creates an incompatibility with C++, which requires it. A void pointer is a pointer that points to an object of unknown type. ...


Memory allocated via malloc is persistent: it will continue to exist until the program terminates or the memory is explicitly deallocated by the programmer (that is, the block is said to be "freed"). This is achieved by use of the free function. Its prototype is

 void free(void *pointer); 

which releases the block of memory pointed to by pointer. pointer must have been previously returned by malloc or calloc (or a function which uses one of these, eg strdup), and must only be passed to free once.


Usage example

The standard method of creating an array of ten integers on the stack is: For the microarray in genetics, see SNP array. ...

 int array[10]; 

To allocate a similar array dynamically, the following code could be used:

 /* Allocate space for an array with ten elements of type int. */ int *ptr = malloc(10 * sizeof (int)); if (ptr == NULL) { /* Memory could not be allocated, so print an error and exit. */ fprintf(stderr, "Couldn't allocate memoryn"); exit(EXIT_FAILURE); } /* Allocation succeeded. */ 

Related functions

calloc

malloc returns a block of memory that is allocated for the programmer to use, but is uninitialized. The memory is usually initialized by hand if necessary -- either via the memset function, or by one or more assignment statements that dereference the pointer. An alternative is to use the calloc function, which allocates memory and then initializes it. Its prototype is

 void *calloc(size_t nelements, size_t bytes); 

which allocates a region of memory large enough to hold nelements of size bytes each. The allocated region is initialized to zero.


realloc

It is often useful to be able to grow or shrink a block of memory. This can be done using realloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is

 void *realloc(void *pointer, size_t size); 

Common errors

The improper use of malloc and related functions can frequently be a source of bugs.


Allocation failure

malloc is not guaranteed to succeed — if there is no memory available, or if the program has exceeded the amount of memory it is allowed to reference, malloc will return a NULL pointer. Depending on the nature of the underlying environment, this may or may not be a likely occurrence. Many programs do not check for malloc failure. Such a program would attempt to use the NULL pointer returned by malloc as if it pointed to allocated memory, and the program would crash. This has traditionally been considered an incorrect design, although it remains common, as memory allocation failures only occur rarely in most situations, and the program frequently can do nothing better than to exit anyway. Checking for allocation failure is more important when implementing libraries — since the library might be used in low-memory environments, it is usually considered good practice to return memory allocation failures to the program using the library and allow it to choose whether to attempt to handle the error.


Memory leaks

When a call to malloc, calloc or realloc succeeds, the return value of the call should eventually be passed to the free function. This releases the allocated memory, allowing it to be reused to satisfy other memory allocation requests. If this is not done, the allocated memory will not be released until the process exits — in other words, a memory leak will occur. Typically, memory leaks are caused by losing track of pointers, for example not using a temporary pointer for the return value of realloc, which may lead to the original pointer being overwritten with NULL, for example: In computer science, a memory leak is a particular kind of unintentional memory consumption by a computer program where the program fails to release memory when no longer needed. ...

 void *ptr; size_t size = BUFSIZ; ptr = malloc(size); /* some further execution happens here... */ /* now the buffer size needs to be doubled */ if (size > SIZE_MAX / 2) { /* handle overflow error */ /* ... */ return (1); } size *= 2; ptr = realloc(ptr, size); if (ptr == NULL) { /* the realloc failed (it returned NULL), but the original address in ptr has been lost so the memory cannot be freed and a leak has occurred */ /* ... */ } /* ... */ 

Use after free

After a pointer has been passed to free, it becomes a dangling pointer: it references a region of memory with undefined content, which may not be available for use. However, nothing prevents the pointer from being used. For example: Dangling pointers in programming are pointers whose objects have since been deleted or deallocated, without modifying the value of the pointer. ...

 int *ptr = malloc(sizeof (int)); free(ptr); *ptr = 0; /* Undefined behavior! */ 

Code like this has undefined behavior: its effect may vary. Commonly, the system may have reused freed memory for other purposes. Therefore, writing through a pointer to a deallocated region of memory may result in overwriting another piece of data somewhere else in the program. Depending on what data is overwritten, this may result in data corruption or cause the program to crash at a later time. A particularly bad example of this problem is if the same pointer is passed to free twice, known as a double free. To avoid this, some programmers set pointers to NULL after passing them to free: free(NULL) is safe (it does nothing).[4] However, this will not protect other aliases to the same pointer from being doubly freed.


Freeing unallocated memory

Another problem is when free is passed an address that wasn't allocated by malloc. This can be caused when a pointer to a literal string or the name of a declared array is passed to free, for example:

 char *msg = "Default message"; int tbl[100]; 

passing either of the above pointers to free will result in undefined behaviour.


Implementations

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 both malloc and operator new in C++. Hence, we will call this the allocator rather than malloc. (However, note that it is never proper for C++ to treat malloc and new interchangeably. For example, free cannot be used to release memory that was allocated with new.[5]) C++ (pronounced see plus plus, IPA: ) is a general-purpose programming language with high-level and low-level capabilities. ...


Heap-based

Implementation of the allocator on IA-32 architectures is commonly done using the heap, or data segment. The allocator will usually expand and contract the heap to fulfill allocation requests. It has been suggested that this article or section be merged with X86 assembly language. ...


The heap method suffers from a few inherent flaws, stemming entirely from fragmentation. Like any method of memory allocation, the heap will become fragmented; that is, there will be sections of used and unused memory in the allocated space on the heap. A good allocator will attempt to find an unused area of already allocated memory to use before resorting to expanding the heap. However, due to performance it can be impossible to use an allocator in a real time system and a memory pool must be deployed instead. In computer storage, there are three related uses of the term fragmentation: external fragmentation, internal fragmentation, and data fragmentation, all related to storage. ... Memory pools allow dynamic memory allocation comparable to malloc or the Operator new in C++. As those implementations suffer from fragmentation because of variable block sizes, it can be impossible to use them in a real time system due to performance. ...


The major problem with this method is that the heap has only two significant attributes: base, or the beginning of the heap in virtual memory space; and length, or its size. The heap requires enough system memory to fill its entire length, and its base can never change. Thus, any large areas of unused memory are wasted. The heap can get "stuck" in this position if a small used segment exists at the end of the heap, which could waste any magnitude of address space, from a few megabytes to a few hundred.


The glibc allocator

The GNU C library (glibc) uses both brk and mmap on the Linux operating system. The brk system call will change the size of the heap to be larger or smaller as needed, while the mmap system call will be used when extremely large segments are allocated. The heap method suffers the same flaws as any other, while the mmap method may avert problems with huge buffers trapping a small allocation at the end after their expiration. Glibc is the GNU projects C standard library. ... In computing, mmap() is a POSIX-compliant Unix system call that maps files or devices into memory. ... This article is about operating systems that use the Linux kernel. ...


The mmap method has its own flaws: it always allocates a segment by mapping entire pages. Mapping even a single byte will use an entire page which is usually 4096 bytes. Although this is usually quite acceptable, many architectures provide large page support (4 MiB or 2 MiB with PAE on IA-32). The combination of this method with large pages can potentially waste vast amounts of memory. The advantage to the mmap method is that when the segment is freed, the memory is returned to the system immediately. In a context of computer virtual memory, a page, memory page, or virtual page is a fixed-length block of main memory, that is contiguous in both physical memory addressing and virtual memory addressing. ... In computing, Physical Address Extension (PAE) refers to a feature of x86 processors that allows for up to 64 gigabytes of physical memory to be used in 32-bit systems, given appropriate operating system support. ...


OpenBSD's malloc

OpenBSD's implementation of the malloc function makes use of mmap. For requests greater in size than one page, the entire allocation is retrieved using mmap; smaller sizes are assigned from memory pools maintained by malloc within a number of "bucket pages," also allocated with mmap. On a call to free, memory is released and unmapped from the process address space using munmap. This system is designed to improve security by taking advantage of the address space layout randomization and gap page features implemented as part of OpenBSD's mmap system call, and to detect use-after-free bugs—as a large memory allocation is completely unmapped after it is freed, further use causes a segmentation fault and termination of the program. OpenBSD is a Unix-like computer operating system descended from Berkeley Software Distribution (BSD), a Unix derivative developed at the University of California, Berkeley. ... In computing, an address space defines a range of discrete addresses, each of which may correspond to a physical or virtual memory register, a network host, peripheral device, disk sector or other logical or physical entity. ... Address space layout randomization (ASLR) is a computer security technique which involves arranging the positions of key data areas, usually including the base of the executable and position of libraries, heap, and stack, randomly in a process address space. ... In computing, a system call is the mechanism used by an application program to request service from the operating system. ... It has been suggested that Access violation be merged into this article or section. ...


Hoard's malloc

The Hoard memory allocator is an allocator whose goal is scalable memory allocation performance. Like OpenBSD's allocator, Hoard uses mmap exclusively, but manages memory in chunks of 64K 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. The Hoard memory allocator, or Hoard, is a memory allocator for Linux, Solaris, Microsoft Windows and other operating systems. ...


Allocation size limits

The largest possible memory block malloc can 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 a size_t type, which is an implementation-dependent unsigned integer representing the size of an area of memory. The maximum value is (size_t) −1, or the constant SIZE_MAX in the C99 standard. The C standards guarantee that a certain minimum (0x7FFF in C90, 0xFFFF in C99) for at least one object can be allocated. The correct title of this article is . ...


See also

In computer security and programming, a buffer overflow, or buffer overrun, is a programming error which may result in a memory access exception and program termination, or in the event of the user being malicious, a possible breach of system security. ... A memory debugger is a programming tool for finding memory leaks and buffer overflows. ... In Unix-like operating systems, mprotect() is a POSIX system call for controlling memory protections. ... Wikipedia does not yet have an article with this exact name. ... Aard (Dutch for Earth) is a programming tool to check memory use for C++ programs. ... In the C++ programming language, new is an operator that allows dynamic memory allocation on the heap. ...

References

is the 68th day of the year (69th in leap years) in the Gregorian calendar. ... Year 2007 (MMVII) is the current year, a common year starting on Monday of the Gregorian calendar and the AD/CE era in the 21st century. ... is the 68th day of the year (69th in leap years) in the Gregorian calendar. ... Year 2007 (MMVII) is the current year, a common year starting on Monday of the Gregorian calendar and the AD/CE era in the 21st century. ... is the 68th day of the year (69th in leap years) in the Gregorian calendar. ... Year 2007 (MMVII) is the current year, a common year starting on Monday of the Gregorian calendar and the AD/CE era in the 21st century. ... is the 68th day of the year (69th in leap years) in the Gregorian calendar. ... Year 2007 (MMVII) is the current year, a common year starting on Monday of the Gregorian calendar and the AD/CE era in the 21st century. ... is the 68th day of the year (69th in leap years) in the Gregorian calendar. ... Year 2007 (MMVII) is the current year, a common year starting on Monday of the Gregorian calendar and the AD/CE era in the 21st century. ...

External links


  Results from FactBites:
 
Malloc - definition of Malloc in Encyclopedia (708 words)
malloc is a function for allocating memory dynamically in the C programming language.
Without malloc, memory allocation must be done "at once".
Note that usually, the same allocator used for malloc() is also used for the new[] keyword in C++.
Malloc - Wikipedia, the free encyclopedia (1582 words)
The initial letter is capitalized due to technical restrictions.
The same dynamic memory allocator is often used to implement both malloc and
Implementation of the allocator on IA-32 architectures is commonly done using the heap, or data segment.
  More results at FactBites »

 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m