新操作是否连续分配了内存? [英] Is the memory allocated by new operated consecutive?

查看:82
本文介绍了新操作是否连续分配了内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我想在c ++中知道一个新操作分配的内存是否连续...

as the title says, I want to know in c++, whether the memory allocated by one new operation is consecutive...

推荐答案

BYTE* data = new BYTE[size];

在此代码中,无论大小如何,返回的内存区域都是连续的.如果堆管理器无法分配 size 大小的连续内存,那么它将失败.将会返回一个异常(或 malloc 中的NULL).

In this code, whatever size is given, the returned memory region is consecutive. If the heap manager can't allocate consecutive memory of size, it's fail. an exception (or NULL in malloc) will be returned.

程序员总是会在进程的地址空间中看到连续(而且是无限的:-)内存的错觉.这就是虚拟内存为程序员提供的功能.

Programmers will always see the illusion of consecutive (and yes, infinite :-) memory in a process's address space. This is what virtual memory provides to programmers.

请注意,程序员(除少数嵌入式系统以外)始终会看到虚拟内存.但是,实际上可以以任意方式在物理内存中映射连续内存(以页面"大小的粒度,通常为4KB).您看不到该映射,而且大多数情况下您不需要了解它(非常具体的页面级优化除外).

Note that programmers (other than a few embedded systems) always see virtual memory. However, virtually consecutive memory could be mapped (in granularity of 'page' size, which is typically 4KB) in physical memory in arbitrary fashion. That mapping, you can't see, and mostly you don't need to understand it (except for very specific page-level optimizations).

那呢?

BYTE* data1 = new BYTE[size1];
BYTE* data2 = new BYTE[size2];

当然,您不能说 data1 data2 的相对地址.通常是不确定的.它取决于堆管理器(例如, malloc ,通常 new 仅被包装为 malloc )策略和请求时的当前堆状态.

Sure, you can't say the relative address of data1 and data2. It's generally non-deterministic. It depends on heap manager (such as malloc, often new is just wrapped malloc) policies and current heap status when a request was made.

这篇关于新操作是否连续分配了内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆