![]() |
Memory Management In C and C + +
Original Non English Version here.
For simple applications, it's enough just to rely on automatic memory management through local variables. But once the data become larger, it is no longer imperative to request memory from the heap and manage. ContentA function familiesIn principle, belong to the memory always two parts. First, an area of memory are requested, and second, the memory used at the end of the work be returned. For this reason, memory management functions normally exist in pairs, sharing the work. When working with C + + objects is yet to fill the requested memory with sensible starting values or the data of the object at the end of the work to clean up again. For this purpose, there are constructors and destructors that are called automatically to suit the use or management must be handled manually. Over time, various function pairs were developed, which can be requested and memory freed. It is particularly important to the different methods of memory management not to interfere with each other. In the simplest case, it is "just" a memory leak (if the sharing function "just forget" to call the Objektdestruktor or returns too little heap memory), in the worst case, can not be predicted what will make the program (for example, it can happen that the release function tries to interpret something in her memory structure unknown). For this reason, libraries, heap areas and request the user to pass, always provide a compatible release function, which is suitable to its own working memory - or in the documentation at least set the method of the memory they use. 1.1 malloc () and free () This family dates back to C and has been for reasons of compatibility for C + +: Accepted
Note: The function realloc () can also single-handedly take over the entire memory of a program by its parameters are set appropriately: Code:
char* str = realloc (NULL, 100);/ / memory allocation For C + +, a new mechanism for memory management, which provides a better approach to the class. Unlike malloc () / free () the memory areas are regarded as objects of arbitrary classes, and now initialized with an appropriate constructor.
Another advantage of new and delete is the fact that they can be overridden by the user. This requires either a global (for every new call) or static member function (for their own class, and all children) "operator new ()" or "operator delete ()", or the free memory can request. These operators work with unstructured data fields - the call to constructors and destructors are independently: Code:
void* operator new(size_t s) Note: "operator new" and "operator delete" operate with bare areas of memory. The constructor and destructor of the object involved is called when operator new has come back before or operator delete is called. Caution: Do not overcharge the global operators only if you are absolutely sure what you want to achieve. The global version of operator new and operator delete takes really ANY memory request within the program - and in contrast to klasseninternen operators can not here from the predefined memory access operators. Another typical application for operator new and operator delete is to use a pool manager: in order to save computing time, the memory of precaution required in larger blocks, replaced and forwarded as needed to the program. From the program of shared memory is not returned to the system, but also for future requirements repealed. 1.3 New [] and delete [] In parallel with new and delete, playing with various objects, there are versions to manage whole object array:
Note: new [] remember (just like malloc ()) internally the size of the allocated memory. However, there is no portable way to access this information. Note: Despite the name similarity is not guaranteed that new / delete and new [] / delete [] are compatible with each other. So try NIE, the two mix with each other. 1.4 Other families Many libraries define your own function pairs in order to request and release memory, eg VirtualAlloc () / manage Virtual Free () from the WinAPI, the memory in the "shared memory". All such families function in common is that they consist of at least two functions - one for requesting memory, one for release. Analogous to the malloc () family may be added other features that can reorganize the managed memory. Because different memory strategies are not necessarily compatible with each other, you should always use the correct release function if you need more memory not yours. Therefore, it is usually a good idea to have a program on a strategy and set within this largely unsustainable. If that is not generally possible, should know where he is to his memory relate to each case are set for each pointer used. Even in the standard library yet another function family is defined, which can be used to manage temporary storage:
AllocatorsThe containers of the STL default to new [] and delete [] to know the memory request for their elements. However, as it should be possible to switch to a different memory management, this behavior had been moved into so-called allocators - these can be interchanged, to use a different memory behavior. In addition, each container class as the last template parameter an indication of the allocator class. The default value for this is std:: allocator <T> - this allocates memory using new [] and returns it with delete [] free again. An allocator has to be used with the STL, provide some basic methods and definitions. If you write an allocator for its own purposes, the requirements may be lower. 2.1 management The most important are the Allokatorklasse course, the functions that can manage the memory:
Custom allocators are generally allocate the methods (), deallocate () and max_size () override to implement the storage strategy. construct () and destroy () are likely to differ only in the rarest cases, by the standard version: Code:
template<typename T> In order to offer the ability to store various objects that contains a substructure Allokatorklasse called "Rebind. This is used as the associative container classes, which receive as an allocator template parameter <T>, but need an internal TreeNode allocator <<T>>. This structure is pretty simple and serves only to "packaging" of the alternate type: Code:
template<typename T> Code:
template<typename T,typename A = std:: allocator <T>> Different allocators can be compared with the operators == and! =. These features will be released equality that two allocators are interchangeable - is requested by a memory on b again. For example, building allocators, to delete the new /, are interchangeable, as is required for the delete-object call no tax. In contrast pool allocators are limited interchangeable because each allocator manages its own list of reserve memory. Note: STL compatible allocators have to be interchangeable. reduce most of the comparison operators to a "return true reason," or return false; ". 2.4 Type definitions Allocators also define some basic types used by the connected container classes continue:
Auxiliary functions for memory managementIn addition to the standard library allocators defines some utility functions that can deal with non-uninitialized memory. These serve as a logical extension of memset () and memcpy ():
Code:
T * data =::operator new[] (n *sizeof(T)); Code:
* p myType = (myType *) malloc (sizeof(myType)); 3.1 Rohspeicher iterators Full Name: Code:
template<typename OutIt,typename T> The template parameter of this class are, first, an output iterator that is used as the basis for the iterator arithmetic (usually enough for this one 'T *') and second, the data type used. 3.2 Functions of the C library Unlike C + + interprets the C library typically anything in the memory areas, which it manages. Logically, obtained from malloc () a bunch of bytes with no internal structure. Then it depends on the programmer, as he fills the memory and interpreted. To process this naked memory areas can be either the malloc () pointer obtained in the "right" type casting and processing of hand or some ready-made functions of the C library (memcpy (), memset (), etc.), or (with restrictions ) the string processing functions (strcpy (), strcat () to take, etc.) to help. Note: Try to be better not to interpret bare memory than C + + objects. Most methods expect an existing basic structure and lead to undefined behavior if they get junk data set before. Smart PointerThe management of heap memory (no matter how it was obtained) on bare hands always suffer the same problem - no one can verify when and by whom the memory must be freed. Forget the last owner of the release shows a memory leak, because no one knows more about the existence of the memory block. If the memory released too early, you get access violations and undefined behavior if other users want to access the shared memory. A solution to this problem is to make the pointer itself to instruct the memory management, instead of bare hands by so-called "smart pointer" is used. These differ in principle three different approaches to control the access and control:
The operation and characteristics of the different smart pointer classes was some time ago in the article "Smart pointer" peter's declared. Note: Normal smart pointer classes to a specific memory function (usually new / delete and new [] / delete []) defined and therefore expect that their managed storage "was created correctly." The above smart pointer classes (except auto_ptr to find) into the Boost Library or TR1 extension of the standard. The auto_ptr class is part of the C + + Standard Library. STL ContainerWhom the whole burden of memory management is too complicated, it can also make it easier - and use the various classes of the STL containers. All the container take care of their own so to provide enough memory and to manage, so that the user no longer needs to worry about where their data is housed. The usable container classes differ mainly from the perspective of memory in it, the strategy that they require memory and organize:
Note: This will of course depend on the type of allocator, where the containers maintain their memory. |
Re: Memory Management In C and C + +
I see the same Article in some other language here but could not see any english version of the same.
Added the credit of the article. |
Re: Memory Management In C and C + +
yeah, thanks shabbir for adding the credit!
:) |
Re: Memory Management In C and C + +
The pleasure is all mine.
|
Re: Memory Management In C and C + +
Nominate this article for Article of the month - Jun 2010
|
Re: Memory Management In C and C + +
Vote for this Article for Article of the month - Jun 2010
|
Re: Memory Management In C and C + +
Nice translation made...
:) |
Re: Memory Management In C and C + +
Quote:
thanks pankaj.sea.... :) |
| All times are GMT +5.5. The time now is 12:51. |