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?
Although 100*sizeof(int) = 400 bytes (on a 32 bit system) is not a big chunk of memory; If you do through malloc();
int *x = (int *) malloc(100 * sizeof(int));
Modern day OS memory manager just looks at its allocation table before it returns you an address of logical contigous memory and do an appropriate marking to reflect the allocation to the process in its table. That's your allocation, almost immediately.
However, when the area is greater that a page size usually 4k on a 32-bit system and 8k over 64-bit systems; this allocation to actual physical memory is delayed till you actually write data on them. This is because the COW feature (Copy On Write). However the malloc() would return almost immediate with just a virtual memory address only.
This is how such allocations are tracked:
struct task_struct has a field like struct mm_struct *mm, *active_mm;
//which on expanding under file include/linux/mm_types.h, looks like:
struct mm_struct {
struct vm_area_struct * mmap; /* list of VMAs */
struct rb_root mm_rb;
struct vm_area_struct * mmap_cache; /* last find_vma result */
unsigned long (*get_unmapped_area) (struct file *filp,
unsigned long addr, unsigned long len,
unsigned long pgoff, unsigned long flags);
void (*unmap_area) (struct mm_struct *mm, unsigned long addr);
unsigned long mmap_base; /* base of mmap area */
unsigned long task_size; /* size of task vm space */
unsigned long cached_hole_size; /* if non-zero, the largest hole below free_area_cache */
unsigned long free_area_cache; /* first hole of size cached_hole_size or larger */
pgd_t * pgd;
atomic_t mm_users; /* How many users with user space? */
atomic_t mm_count; /* How many references to "struct mm_struct" (users count as 1) */
int map_count; /* number of VMAs */
struct rw_semaphore mmap_sem;
spinlock_t page_table_lock; /* Protects page tables and some counters */
struct list_head mmlist; /* List of maybe swapped mm's. These are globally strung
* together off init_mm.mmlist, and are protected
* by mmlist_lock
*/
/* Special counters, in some configurations protected by the
* page_table_lock, in other configurations by being atomic.
*/
mm_counter_t _file_rss;
mm_counter_t _anon_rss;
unsigned long hiwater_rss; /* High-watermark of RSS usage */
unsigned long hiwater_vm; /* High-water virtual memory usage */
unsigned long total_vm, locked_vm, shared_vm, exec_vm;
...
...
}
The field struct vm_area_struct * mmap; /* list of VMAs */
keeps track of the process memory area all the times.
That's 1000 integers, not 100.
But yes. You get the entire chunk at once.
If you've freed memory before, it's possible you'll get a recycled chunk instead of a brand-new one.