What are the memory segments in C program?

An application program binary file is stored in ELF format in Linux and COFF format in Windows. These have segments for different segments of memory. CODE or .TEXT section holds the binary executable code. Constants, Global, static, const data variables are stored in DATA section. BSS section stores the uninitialized global or strict variables. Next segment to the data area is the heap and dynamic memory and program stack.

BSS, heap, and stack segments are created at runtime. Heap starts after data and BSS segments. Heap grows up and it ends till the stack area starting. Now stack area is actually at the top of the memory area. Stack can grow downwards or upwards depending on the processor architecture.

CODE DATA BSS HEAP STACK segment of program

What is stack memory segment in C program?

CPU uses stack to pass parameters and to save return address before jumping to next function call. It also uses stack memory for loading and storing local variables. Below is a stack grow example of a function call which has this following prototype-

int function (int argument1, int arrgument2)
{
  int local;
  ....
  
}

Stack Grows in UP or Down

Here we have a local variable Local. Program calls more and more inner functions, call frame grows. With the above prototype compiler pushes argument2 then argument1 and then call the function. Call instruction pushes the return address and further inside the function compiler pushes BP. Compiler will put local after this. Now as stack grows in a perticuler direction so after each and every inner function call, address of the local would be either increasing or decreasing position. If we compare the address values we would definitely get the direction details. Here is a small C code example. Here we are passing the address of a local of an outer function to an inner function call. Now as we called a function stack has grown. Next is compare the address of two locals.

C program to check stack grows up or down

int dummy_call(void * p)
{
  unsigned int local;
  if (&local < p) {
    return -1;
  } else {
    return 1;
  }
}
int stack_grows(void)
{
  unsigned int local;
  return dummy_call(&local);
}
int main(int argc, char* argv[])
{
  printf("Stack grows in %s direction\n", stack_grows() < 0 ? "Lower" : "Higher");

}


Output:
Stack grows in Lower direction.

Output of stack grows up or down

Output on x86-64:
Stack grows in Lower direction.

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

#