What happens when we try to run a program

Sharan Karthikeyan
3 min readSep 23, 2022

I’m going to write a program in C language and let me show you how the C program works.

Here is the code snippet program.c

When we try to compile the above program we will get an executable file (ex: a.out/program.exe). In Java, we will get a source or byte code.

The above code and compiled code/executable are stored in Secondary memory.

If I try to run the executable file, then the CPU(Central Processing Unit) takes the executable file from secondary memory and places it in the main memory. The execution of the C program’s executable file creates a process.

A program in execution is called a process.

Once, the executable file comes to the main memory, then the main memory allocates 3 sections for that program's run time.

  1. Code Section
  2. Stack memory
  3. Heap memory
The building block of the process. 4x Zoom.

Note: The actual PCB contains many attributes like process-id, process-state, etc. Above diagram, which I created only for easy understanding purpose.

The program’s code is placed in the code section.

CPU executing the process. 2x Zoom.

This is how we execute each process in CPU from RAM.

OS note: CPU won’t access secondary memory directly.

Code Section

All the local variables of the functions are stored in the stack memory. Stack memory is used for static memory allocation in C/C++. Static memory refers to memory allocation that occurs during the compilation process. Static Memory is allocated for declared variables by the compiler. The allocation happens on contiguous blocks of memory.

Whenever the function is executed, the stack frame belonging to that function gets dropped. Allocation and deallocation of the stack memory are handled by the compiler.

If a group of variables belongs to a particular function, then those variables are collectively called a stack frame or activation record.

Stack memory is a temporary memory.

Stack memory and Stack frame

Heap memory is used for dynamic memory allocation. In C / C++, pointer variables are stored in a stack memory and hold the address in the heap memory. For some programming languages, global variables are stored in Heap. The program has to free (ex: free(p);) the heap memory manually.

Memory is allocated in any random order.

It stores the data permanently.

Heap memory

Thank you for reading.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Sharan Karthikeyan
Sharan Karthikeyan

Written by Sharan Karthikeyan

CS student at IIT, Chicago | prev. @Zoho

No responses yet

Write a response