Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc allocates memory more than RAM

I just executed a program that mallocs 13 MB in a 12 MB machine (QEMU Emulated!) . Not just that, i even browsed through the memory and filled junk in it...

void 
large_mem(void) 
{
  #define LONGMEM  13631488
  long long *ptr = (long long *)malloc(LONGMEM);
  long long i;
  if(!ptr) {
     printf("%s(): array allocation of size %lld failed.\n",__func__,LONGMEM);
     ASSERT(0);
  }
  for(i = 0 ; i < LONGMEM ; i++ ) { 
    *(ptr+i)=i;
  }
  free(ptr);
}

How is it possible ? I was expecting a segmentation fault.

like image 820
raj Avatar asked Sep 21 '11 17:09

raj


People also ask

Does malloc allocate memory in RAM?

The “malloc” or “memory allocation” method is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.

How much memory does malloc allocate?

Malloc(12) and malloc(16) allocate 16 bytes for the user, plus an extra 8 bytes for bookkeeping for a total of 24 bytes. Malloc(100) allocates 104 bytes for the user, plus an extra 8 bytes for bookkeeping.

Does malloc allocate physical memory?

TL;DR: malloc returns a virtual address and does NOT allocate physical memory.

What happens when we do malloc?

The malloc command is used to allocate a block of memory. It is also possible to deallocate a block of memory when it is no longer needed. When a block is deallocated, it can be reused by a subsequent malloc command, which allows the system to recycle memory.


2 Answers

It's called virtual memory which is allocated for your program. It's not real memory which you call RAM.

There is a max limit for virtual memory as well, but it's higher than RAM. It's implemented (and defined) by your operating system.

like image 194
Nawaz Avatar answered Oct 01 '22 19:10

Nawaz


This is called as Lazy Allocation.

Most OS like Linux have an Lazy Allocation memory model wherein the returned memory address is a virtual address and the actual allocation only happens at access-time. The OS assumes that it will be able to provide this allocation at access-Time.

The memory allocated by malloc is not backed by real memory until the program actually touches it.

While, since calloc initializes the memory to 0 you can be assured that the OS has already backed the allocation with actual RAM (or swap).

Try using callocand most probably it will return you out of memory unless your swap file/partition is big enough to satisfy the request.

like image 45
Alok Save Avatar answered Oct 01 '22 18:10

Alok Save