The stack versus the heap

What does a program look like that just uses the heap to store its variables? Well, in truth, the stack is still used – you almost can’t avoid using it when designing a program. Here is a piece of C code that is implemented just using stack memory.

#include <stdio.h>

double multiplyIt(double aNum, double multP)
{
    double result;
    result = aNum * multP;
    return result;
}

int main (void)
{
    int i, what=24;
    double isIt[4] = {1.6, 3.2, 6.4, 12.8};

    for (i=0; i<4; i=i+1)
    printf("%.1lf\n", multiplyIt(what,isIt[i]));

    return 0;
}

On lines 12 and 13 of the main() function, three variables are created: two ints, and a double array with 4 elements. These are pushed onto the stack as soon as main() is activated. When the function main exits ,they are all popped off the stack and destroyed. Similarly, the double variable result in function multiplyIt() is pushed onto the stack when multiplyIt() is activated (and popped from the stack when multiplyIt() exits).

In the next example, the same code has been written with the heap in mind.

#include <stdio.h>
#include <stdlib.h>

double *multiplyIt(double *aNum, double *multP)
{
    double *result = malloc(sizeof(double));
    *result = *aNum * *multP;
    return result;
}

int main (void)
{
    int *i = malloc(sizeof(int));
    double *what = malloc(sizeof(int));
    double *result = malloc(sizeof(double));
    double *isIt = malloc(4*sizeof(double));

    *isIt = 1.6;
    *(isIt+1) = 3.2;
    *(isIt+2) = 6.4;
    *(isIt+3) = 12.8;

    *what = 24;

    for (*i=0; *i<4; *i=*i+1)
    {
        result = multiplyIt(what,&isIt[*i]);
        printf("%.1lf\n", *result);
    }

    free(i);
    free(what);
    free(result);
    free(isIt);
    return 0;
}

This program uses malloc() to allocate memory on the heap and then uses free() to deallocate it, which is not such a big deal – but it does take extra effort. All the variables are allocated on the heap: a pointer to an integer, two pointers to doubles, and a pointer to an array of doubles. This is likely the more efficient way of of coding this program, however it much more complex, with all the *’s and &’s all over the place.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s