内存分配查询 [英] Memory Allocation Query

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

问题描述

当我们动态分配内存时,说100个整数,说

int *x = new int(1000);

那么语句完成后是否会立即分配全部内存?

我的意思是页面错误的概念会在这里出现吗?

When we dynamically allocate the memory say 100 integers say

int *x = new int(1000);

then does entire chunk of memory gets allocated at once after the completion of the statement?

I mean will the the concept of page fault come into picture over here?

推荐答案

sarfaraznawaz写道:
sarfaraznawaz wrote:

当我们动态分配内存时,说100个整数说

When we dynamically allocate the memory say 100 integers say

int *x = new int(1000);




当我们要分配100整数时,应使用正确的语法.
您的代码段只是为1(是,一个)整数分配内存,然后使用值1000初始化.正确的语句(用于分配100整数)是:



When we want to allocate 100 integers, we should use the correct syntax.
Your code snippet just allocates memory for 1 (yes, one) integer and then initializes it with the value 1000. The correct statement (for allocating 100 integers) is:

int * x = new int[100];



成功时,它会(立即)为100整数分配连续的内存,失败时,会抛出异常,如 ^ ].



on success, it allocates (at once) contiguous memory for 100 integers, on failure an exception is thrown as specified in documentation of new operator[^].


除了CPallini之外,还有关于页面错误问题"的信息,这完全取决于操作系统.
是否可能出现页面错误,具体取决于分配时内存的分配方式和分段方式.
无论如何,这对程序都是透明的:如果操作系统能够重新安排内存分页以适应您的请求,则将给出您所要求的内容(是的,该块是连续的).无论是直接发生还是在物理空间重新格式化和交换之后发生,都没有证据.
如果操作系统无法满足您的请求,则会抛出std::bad_alloc异常.
默认情况下,这将终止您的程序,但是您可以以不同的方式处理它(例如,您可以通知用户内存不足,以便他可以取消其他一些任务,让更多的内存可用,并回答您重试操作失败)
In addition to CPallini, about the "page fault issue", this is much more a matter of the operating system.
A page fault may arise or not depending on how the memory is allocated and fragmented at the time of allocation.
In any case, this is transparent to the program: if the OS is able to rearrange the memory paging to accommodate your request, then what you asked is given (and yes, the chunk is contiguous). Whether it happens directly or after a physical space reformatting and swapping, is not given in evidence.
If the OS is unable to accommodate your request, a std::bad_alloc exception is thrown.
By default this will terminate your program, but you can handle it differently (for example, you may inform the user that the memory is low, so that he can dismiss some other tasks, letting more memory to be available, and answering you to retry the failed operation)


是的.在这种情况下,所有内容都已分配-因为int是可以完成请求的原始类型.如果您已将100个指针分配给整数,则指针的空间也将立即分配-但不会分配它们指向的整数.
Yes. In this case it is all assigned - because int is a primitive type that it can just complete the request. If you had allocated 100 pointers to integers, the space for the pointers would also have been allocated immediately - but not the ints they point to.


这篇关于内存分配查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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