Question

Let's say I have these variables and pointers. How do I determine which is in stack or heap?

     #include <stdio.h>
     #define SIZE 5


    int main( void ) {

    int *zLkr;                 
    int *aLkr= NULL;
    void *sLkr= NULL;
    int num, k;
    int a[SIZE] = { 1, 2, 3, 4, 5 };
    zLkr = a;

    }
Was it helpful?

Solution

All your variables have automatic scope. They come from the "stack", in that the variables are no longer valid once the function returns.

Named function variables can never come from the "heap" in the sense that you mean it. The memory for a named function variable is always tied to the function scope (or the innermost block scope within the function in which the variable is declared).

A variable can be assigned a value obtained by malloc() or similar dynamic allocation function. The variable then points to an object that exists in the "heap". However, the named pointer variable itself is not in the "heap".

Sometimes the "stack" itself is dynamically allocated. Such as for a thread. Then, the memory used to allocate function local variables running within that thread is in the "heap". However, the variables themselves are still automatic, in that they are invalid once the function returns.

OTHER TIPS

Local variables are allocated on the stack

int main(void)
{    
    int thisVariableIsOnTheStack;

    return 0;
}

Variables from the heap are allocated via malloc somewhere in memory. That memory can be returned to the heap, and reused by a later malloc call.

int main(void)
{
    char *thisVariableIsOnTheHeap = (char *) malloc(100);

    free (thisVariableIsOnTheHeap);
    return 0;
}

Module variables are neither. They have a constant address in memory in one module.

void f1(void)
{
    /* This function doesn't see thisIsAModule */
}

int thisIsaModule = 3;

void f(void)
{
    thisIsaModule *= 2;
}

int main(void)
{
    return thisIsaModule;
}

Global variables are neither. They have a constant value in memory, but can be referred to across modules.

extern int globalVariable;    /* This is set in some other module. */

int main(void)
{
    return globalVariable;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top