Search code examples
c++memory-managementportable-executable

what is the difference between memory allocated by VirtualAlloc and the memory allocated by std::vector


i tried to understand it but all what i understood so far is that using VirtualAlloc can allocate large memory pages for large buffers for example and std::vector too but VirtualAlloc i can commit the page i can set the permission to read,write , or execute and i can't do that with std::vector or can i? am basically trying to allocate memory for building a pe file that i read from my (disk). i also want to use std::vector since its much more modern way of allocating memory since its done automatically by using RAII.


Solution

  • std::vector is a container that manages an array on the back end and provides functions that help you interact with it easily, with the bonus of being able to increase and decrease it's size. This is implemented as part of the C++ Standard Library.

    VirtualAlloc() is a Windows API function and only works on Windows. It allocates page(s) of memory and returns the address of the allocated memory.

    Using std::vector as intended, you don't know the address of the array and should avoid interacting with it directly.

    If you need an array that can expand or shrink in size use an std::vector

    If you need to create a dynamic variable, use a pointer and keyword 'new'

    #include <iostream>
    #include <Windows.h>
    
    int main()
    {
        int* new_ints = new int[300];
    
        //do whatever
    
        delete[] new_ints;
    
        return 0;
    }
    
    

    If you're allocating memory on Windows and using the 'new' keyword doesn't fit your needs, consider using VirtualAlloc() as an alternative. I have never required VirtualAlloc() but I have used VirtualAllocEx() because it allows you to allocate memory in an external process.

    I would not consider std::vector and VirtualAlloc() as alternatives to each other, they both have their individual use cases.