What exactly happens when you new() an object

6 min readDec 26, 2023

All you need to know about memory

The story

“Today I was asked about what happens when new() an object during the interview.” my friend said.

“Ok looks like a basic question, how did you answer,” I said.

“Yes, basic but not easy to answer”. he said.

“I talked about heap, object lifecycle, GC, reference counting,” he said.

“Well that should be good enough for a junior position. You do not have to mention virtual memory, swap, pages all those”.

“Yes but then that’s what my interviewer asked. ‘Do you know what exactly happens on the heap? And what will happen when there is not enough RAM on the heap?’ and I was stuck there”.

“Maybe he wants to touch the limit, should not affect your interview result,” I said.

Let’s discuss it today.

Memory structure

Before we talk about new() let’s look at memory structure when a process starts.

As we can see. after the code has been compiled or interpreted. It will be loaded into RAM. the RAM is located in the user space. 4 parts.

Code. binary code after compilation or interpretation.

Data. static variables(already initialized). for not initialized variables, will be loaded into BSS.

Heap. dynamic RAM allocation. yes, this is where new() object goes.

Stack. when we execute a function, the context (parameters, nested function call) will be loaded here and executed.

So It means that’s all? the heap is located on physical RAM? no.

Virtual Memory

Okay couple of points. before the new() statement we can see 3 things.

  • As we can see, every process has its stack, heap, data, and heap located in Virtual memory.
  • Virtual memory, Page table, and Physical memory are shared by all processes




A channel which focusing on developer growth and self improvement