Click here to Skip to main content
14,970,597 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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?
Posted
Updated 23-Oct-11 23:08pm
v3

sarfaraznawaz wrote:
When we dynamically allocate the memory say 100 integers say
C++
int *x = new int(1000);



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];


on success, it allocates (at once) contiguous memory for 100 integers, on failure an exception is thrown as specified in documentation of new operator[^].
   
Comments
rupeshkp728 24-Oct-11 5:15am
   
Thanks pallini for the reply
The syntax was indeed wrong.
CPallini 24-Oct-11 5:24am
   
You are welcome.
Albert Holguin 24-Oct-11 11:25am
   
+5
CPallini 24-Oct-11 13:41pm
   
Thank you.
Stefan_Lang 25-Oct-11 12:21pm
   
I've recently read a (rather old) note saying that MSVC does not comply to the standard in this, as in MSVC new does never throw and instead returns 0. It didn't say which version it was referring to, nor do I know whether this is (still) true for the newest version(s).
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)
   
Comments
rupeshkp728 24-Oct-11 11:21am
   
Thanks Emilio for the clarification
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.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900