starkk92 starkk92 - 4 months ago 42
C Question

Where in memory are my variables stored in c?

By considering that the memory is divided into four segments: data, heap, stack, and code, where do global variables, static variables, constant data types, local variables (defined and declared in functions), variables (in main function), pointers, and dynamically allocated space (using malloc,calloc) get stored in memory?

I think they would be allocated as follows:


  • global variables -------> data

  • static variables -------> data

  • constant data types -----> code

  • local variables(declared and defined in functions) --------> stack

  • variables declared and defined in main function -----> heap

  • pointers(ex:char *arr,int *arr) -------> heap

  • dynamically allocated space(using malloc,calloc) --------> stack



I am referring to these variables only from the C perspective.

Please correct me if I am wrong as I am newbie to C.

Answer

You got some of these right, but whoever wrote the questions tricked you on at least one question:

  • global variables -------> data (correct)
  • static variables -------> data (correct)
  • 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 (correct)
  • variables declared and defined in main function -----> heap also stack (the teacher was trying to trick you)
  • pointers(ex: char *arr, int *arr) -------> heap 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) --------> stack heap

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