Results 1 to 4 of 4

Thread: The Memory Layout of a C program

  1. #1
    Join Date
    Nov 2009
    Beans
    29

    The Memory Layout of a C program

    A C program is composed of the following pieces:

    Code:
    The Text segment
    
    The Initialized Data Segment
    
    The Uninitialized Data Segment
    
    The Stack
    
    The Heap
    The initialized and uninitialized data segment... do those strictly contain the variables declared/initialized in the main function? Is everything declared/initialized inside another function simply stored on the stack?

    For example:

    Code:
    int foo()
    {
       int j = 2;
       return j;
    }
    
    int main(int argc, char *argv[])
    {
       int k;
       int i = 5;
       k = foo();
    
       return 0;
    }
    Where in the program memory do i,j,and k reside? When does that happen?

  2. #2
    Join Date
    Apr 2008
    Location
    Australia
    Beans
    237
    Distro
    Ubuntu 22.04 Jammy Jellyfish

    Re: The Memory Layout of a C program


  3. #3
    Join Date
    Apr 2009
    Location
    Germany
    Beans
    2,134
    Distro
    Ubuntu Development Release

    Re: The Memory Layout of a C program

    in your example it all lies in the stack.
    the un/initialized segments are for global variables
    The stack and heap are dynamic and grow/shrink as the program progresses. the other segments are constant in size
    Code:
    static int i = 5; //should be in rw initialized segment
    static const char * c = "5"; //should be in read-only initialized segment
    static int j;  //should be in uninitialized segment (but initialized to zero)
    
    int main(...) { // machine instructions are in text segment
      int a;
      int b; // both on stack (frame of main)
      char * c = malloc(4); // pointer is on stack, memory allocated on heap
    }
    
    int f(void) {
      int a; // stack (frame of f)
    }
    Last edited by MadCow108; April 12th, 2010 at 04:30 PM.

  4. #4
    Join Date
    Nov 2009
    Beans
    29

    Re: The Memory Layout of a C program

    Quote Originally Posted by MadCow108 View Post
    in your example it all lies in the stack.
    the un/initialized segments are for global variables
    Thanks! That was exactly what I was unclear about.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •