ghost_9's blog

By ghost_9, history, 17 hours ago, In English
void solve()
{
  int *a = (int*)malloc(1000000000*sizeof(int));//case 1
 
  cout<<1<<endl;
  return;
}

So recently I was asked a question? Why this code compile and does not give RTE, it had to do something with virtual memory if you use a vector array instead it will provide bad_alloc as RTE. So what is the reason behind it or is it compiler dependent?

But the hint was to think about how virtual memory can be used here.

  • Vote: I like it
  • -6
  • Vote: I do not like it

»
17 hours ago, # |
Rev. 2   Vote: I like it +9 Vote: I do not like it

Malloc return value:

On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.

Malloc exceptions (C++):

No-throw guarantee: this function never throws exceptions.

So, malloc just gives a null pointer if it could not allocate memory.