Перейти к содержанию

Способы выделения памяти и их отличия


Рекомендуемые сообщения

VirtualAlloc / HeapAlloc / malloc / new

Первый вариант объяснения:

Each API is for different uses. Each one also requires that you use the correct deallocation/freeing function when you're done with the memory.

VirtualAlloc

A low-level, Windows API that provides lots of options, but is mainly useful for people in fairly specific situations. Can only allocate memory in (edit: not 4KB) larger chunks. There are situations where you need it, but you'll know when you're in one of these situations. One of the most common is if you have to share memory directly with another process. Don't use it for general-purpose memory allocation. Use VirtualFree to deallocate.

HeapAlloc

Allocates whatever size of memory you ask for, not in big chunks than VirtualAlloc. HeapAlloc knows when it needs to call VirtualAlloc and does so for you automatically. Like malloc, but is Windows-only, and provides a couple more options. Suitable for allocating general chunks of memory. Some Windows APIs may require that you use this to allocate memory that you pass to them, or use its companion HeapFree to free memory that they return to you.

malloc

The C way of allocating memory. Prefer this if you are writing in C rather than C++, and you want your code to work on e.g. Unix computers too, or someone specifically says that you need to use it. Doesn't initialise the memory. Suitable for allocating general chunks of memory, like HeapAlloc. A simple API. Use free to deallocate. Visual C++'s malloc calls HeapAlloc.

new

The C++ way of allocating memory. Prefer this if you are writing in C++. It puts an object or objects into the allocated memory, too. Use delete to deallocate. Visual studio's new calls HeapAlloc, and then maybe initialises the objects, depending on how you call it.

There are also a couple of other similar functions like SysAllocString that you may be told you have to use in specific circumstances.

Второй вариант:

VirtualAlloc is a specialized allocation from the OS VM system. Allocation's must be made at on an allocation granularity which is architechture dependent. It is one of the most basic forms of memory allocation. VM allocations can take several forms, memory is not nessisarially dedicated or physically backed in RAM (though it can be). It is typically a special purpose type of allocation, either vary large, needs to be shared, must be aligned on a perticular value (performance reasons) or the caller need not use all of this memory at once... etc...

HeapAlloc is essentially what malloc and new both eventually call. It is designed to be very fast and useable under many different types of scenerio's a general purpose allocation. It is the "Heap" in a classic sence. Heap's are actually setup by a VirtualAlloc, which is what is used to initially reserve space from the OS, after this the space is initialized, which is when various tables, lists's and other data structures are configured to maintain and control the operation of the HEAP. Some of that is in the form of dynamically sizing (growing and shrinking), adapting to perticular usages (frequent allocations of some size), etc..

new and malloc are somewhat the same, malloc is essentially an exact call into HeapAlloc( heap-id-default ); new however, can configure object's for C++. C++ will store vtable's onto the heap for each caller. These vtable's are redirect's for execution and form part of what gives C++ it's oo charicteristics like inheratence, function overloading, etc...

Some other common allocation methods; _alloca() and _malloca are stack based, FileMappings's are really VirtualAlloc'd and set with perticualr bit flags's which designate them FILE.

Most of the time, you should allocate memory in a way which is consistant with the use of that memory ;). new in C++, malloc for C, VirtualAlloc for massive or IPC cases.

*** Note, large memory allocation's by HeapAlloc are actually shipped off to Virtual Alloc after some size (couple hundred k or 16 MB or something I forget, but fairly big :)

*** EDIT I brefly remarked about IPC and VirtualAlloc, there is also something very neat about a related VirtualAlloc which none of the responder's to this question have discussed.

VirtualAlloc Ex is what one process can use to allocate memory in a different process's address space. Most typically, used in combination to get remote execution in the context of another process via CreateRemoteThread (simular to CreateThread, the thread is just run in the other process).

Тот кто усвоил - молодец.

  • Плюс 1
Ссылка на комментарий
Поделиться на другие сайты

Вольный перевод. Первый вариант:

Каждая функция имеет своё назначение, а ещё нужно каждый раз освобождать выделенную память, как только вы закончили с ней работать.

VirtualAlloc

Низкоуровневая WinAPI-функция, куча фич, но нужна в довольно специфичных ситуациях, потому что низкий уровень - это серьёзно и опасно, можно сломать винду и мозг. Может выделять (резервировать?) память только в участках, больших 4 Кб. Основная ситуация, когда нужно использовать этот вариант - когда мы шарим память между процессами напрямую, в этом типа и специфика. Для освобождения выделенной памяти юзаем VirtualFree.

HeapAlloc

Выделяет память любых размеров, в отличие от VA (видимо, если у процесса было 1 Кб - мы можем ещё хоть 10 Мб в его адресном пространстве выделить). Автоматически вызывает VirtualAlloc, когда ей это необходимо - нам париться не нужно. Похожа на malloc, но работает только в винде, зато фич чуть побольше. Некоторые WinAPI-функции будут требовать, чтобы им для работы предоставляли память, выделенную именно этой функцией, или же использовать HeapFree для очищения той памяти, что пришла в результате работы этих самых WinAPI.

malloc

Эту функцию очень любит C. Функция кросс-платформенная, так что если пишете на чистых сях, а не на плюсах - лучше использовать её - тогда код будет работать в *NIX-системах. Выделяет память, но не инициализирует. Для очищения используем free. В плюсах эта функция вызывает HeapAlloc.

new

Новый способ выделения памяти в плюсах, так что предпочитаем его, если на плюсах пишем. Кладёт объект (или объекты) в выделенную память. Для очищения используем delete или deallocate. В VS эта функция вызывает HeapAlloc, а затем инициализирует (или нет) сложенные в память объекты, в зависимости от способа вызова.

Ещё, конечно, есть парочка похожих функций, типа SysAllocString, но когда их нужно будет использовать - скажет документация.

  • Плюс 1
Ссылка на комментарий
Поделиться на другие сайты

×
×
  • Создать...

Важная информация

Находясь на нашем сайте, Вы автоматически соглашаетесь соблюдать наши Условия использования.