Memory and C – how the stack works

To illustrate memory in C, consider the following program:

 #include <stdio.h>
 double pi = 3.14159;
 double circleArea(double r) 
     return pi * r * r;
 int main(void)
     double area, radius;
     scanf(“%lf”, &radius);
     area = circleArea(radius);
     printf(“Area = %.2f\n”, area);
     return 0;

Now consider the following diagram relating to the programs memory when it is run:


The left portion of the diagram represents the stack up until the point in the program where the user has entered a value for the radius and it has been stored in the variable radius. The value stored in the global variable pi is stored in the static region. The middle portion of the diagram represents the call to the function circleArea, which has created a new frame in the stack showing various internal variables. The right portion of the diagram shows the stack after the call to circleArea has been completed. The function stack frame has been deleted and not the variable area contains the value of the area calculated, which was returned from the function.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.