简体   繁体   English

VirtualAlloc 分配的 memory 和 std::vector 分配的 memory 有什么区别

[英]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?我试图理解它,但到目前为止我所理解的是,使用 VirtualAlloc 可以为大型缓冲区分配大型 memory 页面,例如 std::vector 但 VirtualAlloc 我可以提交页面我可以设置读取、写入或执行,我不能用 std::vector 做到这一点,或者我可以吗? am basically trying to allocate memory for building a pe file that i read from my (disk).我基本上试图分配 memory 来构建我从我的(磁盘)读取的 pe 文件。 i also want to use std::vector since its much more modern way of allocating memory since its done automatically by using RAII.我也想使用 std::vector 因为它更现代的分配 memory 的方式,因为它是通过使用 RAII 自动完成的。

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. std::vector 是一个容器,它在后端管理一个数组,并提供帮助您轻松与其交互的功能,并且能够增加和减少它的大小。 This is implemented as part of the C++ Standard Library.这是作为 C++ 标准库的一部分实现的。

VirtualAlloc() is a Windows API function and only works on Windows. VirtualAlloc() 是 Windows API function 并且仅适用于 ZAEA23489CE3AA9B43006EBB28E0CD。 It allocates page(s) of memory and returns the address of the allocated memory.它分配 memory 的页面并返回分配的 memory 的地址。

Using std::vector as intended, you don't know the address of the array and should avoid interacting with it directly.按预期使用 std::vector,您不知道数组的地址,应避免直接与其交互。

If you need an array that can expand or shrink in size use an std::vector如果您需要一个可以扩展或缩小大小的数组,请使用 std::vector

If you need to create a dynamic variable, use a pointer and keyword 'new'如果您需要创建动态变量,请使用指针和关键字“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.如果您在 Windows 上分配 memory 并且使用 'new' 关键字不符合您的需求,请考虑使用 VirtualAlloc() 作为替代方案。 I have never required VirtualAlloc() but I have used VirtualAllocEx() because it allows you to allocate memory in an external process.我从来不需要 VirtualAlloc(),但我使用了 VirtualAllocEx(),因为它允许您在外部进程中分配 memory。

I would not consider std::vector and VirtualAlloc() as alternatives to each other, they both have their individual use cases.我不会将 std::vector 和 VirtualAlloc() 视为彼此的替代品,它们都有各自的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM