HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, manual memory management refers to the usage of manual instructions by the programmer to identify and deallocate unused objects, or
garbage Garbage, trash, rubbish, or refuse is waste material that is discarded by humans, usually due to a perceived lack of utility. The term generally does not encompass bodily waste products, purely liquid or gaseous wastes, or toxic waste produc ...
. Up until the mid-1990s, the majority of
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s used in industry supported manual memory management, though
garbage collection Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclable m ...
has existed since 1959, when it was introduced with
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
. Today, however, languages with garbage collection such as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
are increasingly popular and the languages
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
and
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...
provide similar functionality through
Automatic Reference Counting Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift programming languages. At compile time, it inserts into the object code messages retain an ...
. The main manually managed languages still in widespread use today are C and
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
– see
C dynamic memory allocation C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely , , , and . The C++ programming language includes t ...
.


Description

Many programming languages use manual techniques to determine when to ''allocate'' a new object from the free store. C uses the
malloc C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely , , , and . The C++ programming language includes ...
function; C++ and Java use the
new New is an adjective referring to something recently made, discovered, or created. New or NEW may refer to: Music * New, singer of K-pop group The Boyz Albums and EPs * ''New'' (album), by Paul McCartney, 2013 * ''New'' (EP), by Regurgitator, ...
operator; and many other languages (such as Python) allocate all objects from the free store. Determining when an object ought to be created (
object creation In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implement ...
) is generally trivial and unproblematic, though techniques such as
object pool The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the po ...
s mean an object may be created before immediate use. The real challenge is
object destruction In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implement ...
– determination of when an object is no longer needed (i.e. is garbage), and arranging for its underlying storage to be returned to the free store for re-use. In manual memory allocation, this is also specified manually by the programmer; via functions such as free() in C, or the delete operator in C++ – this contrasts with automatic destruction of objects held in
automatic variable __NOTOC__ In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or b ...
s, notably (non-static)
local variable In computer science, a local variable is a Variable (programming), variable that is given ''local scope (programming), scope''. A local variable reference in the subroutine, function or block (programming), block in which it is declared overrides ...
s of functions, which are destroyed at the end of their scope in C and C++.


Manual memory management techniques

For example * malloc/free * Memory arena * scratch buffer * ...


Manual management and correctness

Manual memory management is known to enable several major classes of bugs into a program when used incorrectly, notably violations of
memory safety Memory safety is the state of being protected from various software bugs and Vulnerability (computing), security vulnerabilities when dealing with random-access memory, memory access, such as buffer overflows and dangling pointers. For example, J ...
or
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that Computer memory, memory which is no longer needed is not released. A memory leak may also happe ...
s. These are a significant source of
security bug Security is protection from, or resilience against, potential harm (or other unwanted Coercion, coercive change) caused by others, by restraining the freedom of others to act. Beneficiaries (technically referents) of security may be of persons an ...
s. * When an unused object is never released back to the free store, this is known as a
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that Computer memory, memory which is no longer needed is not released. A memory leak may also happe ...
. In some cases, memory leaks may be tolerable, such as a program which "leaks" a bounded amount of memory over its lifetime, or a short-running program which relies on an
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also in ...
to deallocate its resources when it terminates. However, in many cases memory leaks occur in long-running programs, and in such cases an ''unbounded'' amount of memory is leaked. When this occurs, the size of the available free store continues to decrease over time; when it is finally exhausted, the program then crashes. * Catastrophic failure of the
dynamic memory management Memory management is a form of resource management applied to computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and free it for reuse when ...
system may result when an object's backing memory is deleted out from under it more than once; an object is explicitly destroyed more than once; when, while using a pointer to manipulate an object ''not'' allocated on the free store, a programmer attempts to release said pointer's target object's backing memory; or when, while manipulating an object via a pointer to another, arbitrary area of memory managed by an unknown external task, thread, or process, a programmer corrupts that object's state, possibly in such a way as to write outside of its bounds and corrupt its memory management data. The result of such actions can include
heap corruption Memory corruption occurs in a computer program when the contents of a memory location are modified due to programmatic behavior that exceeds the intention of the original programmer or program/language constructs; this is termed as violation of ...
, premature destruction of a ''different'' (and newly created) object which happens to occupy the same location in memory as the multiply deleted object, program crashes due to a
segmentation fault In computing, a segmentation fault (often shortened to segfault) or access violation is a fault, or failure condition, raised by hardware with memory protection, notifying an operating system (OS) the software has attempted to access a restricte ...
(violation of
memory protection Memory protection is a way to control memory access rights on a computer, and is a part of most modern instruction set architectures and operating systems. The main purpose of memory protection is to prevent a process from accessing memory that ha ...
,) and other forms of
undefined behavior In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres. This is different from unspecified behavior, ...
. * Pointers to deleted objects become
wild pointer Wild, wild, wilds or wild may refer to: Common meanings * Wild animal * Wilderness, a wild natural environment * Wildness, the quality of being wild or untamed Art, media and entertainment Film and television * ''Wild'' (2014 film), a 2014 Am ...
s if used post-deletion; attempting to use such pointers can result in difficult-to-diagnose bugs. Languages which exclusively use
garbage collection Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclable m ...
are known to avoid the last two classes of defects. Memory leaks can still occur (and bounded leaks frequently occur with generational or conservative garbage collection), but are generally less severe than memory leaks in manual systems.


Resource Acquisition Is Initialization

Manual memory management has one correctness advantage, which is that it allows automatic
resource management In organizational studies, resource management is the efficient and effective development of an organization's resources when they are needed. Such resources may include the financial resources, inventory, human skills, production resources, or i ...
via the Resource Acquisition Is Initialization (RAII) paradigm. This arises when objects own scarce
system resource In computing, a system resource, or simple resource, is any physical or virtual component of limited availability within a computer system. All connected devices and internal system components are resources. Virtual system resources include fi ...
s (like graphics resources, file handles, or database connections) which must be relinquished when an object is destroyed – when the lifetime of the resource ownership should be tied to the lifetime of the object. Languages with manual management can arrange this by acquiring the resource during object initialization (in the constructor), and releasing during object destruction (in the destructor), which occurs at a precise time. This is known as Resource Acquisition Is Initialization. This can also be used with deterministic
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, referenc ...
. In C++, this ability is put to further use to automate memory deallocation within an otherwise-manual framework, use of the
shared_ptr In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce bugs caused by the misuse of poin ...
template in the language's standard library to perform memory management is a common paradigm. shared_ptr is ''not'' suitable for all object usage patterns, however. This approach is not usable in most garbage collected languages – notably tracing garbage collectors or more advanced reference counting – due to finalization being non-deterministic, and sometimes not occurring at all. That is, it is difficult to define (or determine) when or if a
finalizer In computer science, a finalizer or finalize method is a special method that performs finalization, generally some form of cleanup. A finalizer is executed during object destruction, prior to the object being deallocated, and is complementary to ...
method might be called; this is commonly known as the finalizer problem. Java and other GC'd languages frequently use manual management for scarce system resources ''besides'' memory via the
dispose pattern In object-oriented programming, the dispose pattern is a design pattern for resource management. In this pattern, a resource is held by an object, and released by calling a conventional method – usually called close, dispose, free, release dep ...
: any object which manages resources is expected to implement the dispose() method, which releases any such resources and marks the object as inactive. Programmers are expected to invoke dispose() manually as appropriate to prevent "leaking" of scarce graphics resources. Depending on the finalize() method (how Java implements finalizers) to release graphics resources is widely viewed as poor programming practice among Java programmers, and similarly the analogous __del__() method in Python cannot be relied on for releasing resources. For stack resources (resources acquired and released within a single block of code), this can be automated by various language constructs, such as Python's with, C#'s using or Java's try-with-resources.


Performance

Many advocates of manual memory management argue that it affords superior performance when compared to automatic techniques such as
garbage collection Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclable m ...
. Traditionally latency was the biggest advantage, but this is no longer the case. Manual allocation frequently has superior
locality of reference In computer science, locality of reference, also known as the principle of locality, is the tendency of a processor to access the same set of memory locations repetitively over a short period of time. There are two basic types of reference localit ...
. Manual allocation is also known to be more appropriate for systems where memory is a scarce resource, due to faster reclamation. Memory systems can and do frequently "thrash" as the size of a program's
working set Working set is a concept in computer science which defines the amount of memory that a process requires in a given time interval. Definition Peter Denning (1968) defines "the working set of information W(t, \tau) of a process at time t to be the ...
approaches the size of available memory; unused objects in a garbage-collected system remain in an unreclaimed state for longer than in manually managed systems, because they are not immediately reclaimed, increasing the effective working set size. Manual management has a number of documented performance ''disadvantages'': * Calls to delete and such incur an overhead each time they are made, this overhead can be amortized in garbage collection cycles. This is especially true of multithreaded applications, where delete calls must be synchronized. * The allocation routine may be more complicated, and slower. Some garbage collection schemes, such as those with
heap Heap or HEAP may refer to: Computing and mathematics * Heap (data structure), a data structure commonly used to implement a priority queue * Heap (mathematics), a generalization of a group * Heap (programming) (or free store), an area of memory f ...
compaction, can maintain the free store as a simple array of memory (as opposed to the complicated implementations required by manual management schemes). Latency is a debated point that has changed over time, with early garbage collectors and simple implementations performing very poorly compared to manual memory management, but sophisticated modern garbage collectors often performing as well or better than manual memory management. Manual allocation does not suffer from the long "pause" times that occur in simple stop-the-world garbage collection, although modern garbage collectors have collection cycles which are often not noticeable. Manual memory management and garbage collection both suffer from potentially unbounded deallocation times – manual memory management because deallocating a single object may require deallocating its members, and recursively its members' members, etc., while garbage collection may have long collection cycles. This is especially an issue in
real time Real-time or real time describes various operations in computing or other processes that must guarantee response times within a specified time (deadline), usually a relatively short time. A real-time process is generally one that happens in defined ...
systems, where unbounded collection cycles are generally unacceptable; real-time garbage collection is possible by pausing the garbage collector, while real-time manual memory management requires avoiding large deallocations, or manually pausing deallocation.


References

*


External links


The Memory Management Reference
* Richard Jones and Rafael Lins, ''Garbage Collection: Algorithms for Automated Dynamic Memory Management'', Wiley and Sons (1996), {{DEFAULTSORT:Manual Memory Management Memory management