Search code examples
cmemory-managementramrom

where in memory are this variables stored on c?


If I have code like this:

const int a=2;
int b;
int main()
{
const int c=4
static int d;
int e;
int f=5;
}

Where in memory (stack, data, heap) are these variables stored(especially the local undefined variable e) ? undefined local variable e will have a garbage value ( where did it come from?)


Solution

    • global variables -------> data
    • static variables -------> data
    • constant data types -----> code and/or data. Consider string literals for a situation when a constant itself would be stored in the data segment, and references to it would be embedded in the code
    • local variables(declared and defined in functions) --------> stack
    • variables declared and defined in main function -----> stack
    • pointers(ex: char *arr, int *arr) -------> data or stack, depending on the context. C lets you declare a global or a static pointer, in which case the pointer itself would end up in the data segment.
    • dynamically allocated space(using malloc, calloc, realloc) --------> heap

    It is worth mentioning that "stack" is officially called "automatic storage class".