Where do your variables live?

Let's discuss stack and heap memory allocation in C with some sample code.

  1. Stack Allocation: Stack memory is used for storing local variables and function call information. The compiler automatically manages it.

     #include <stdio.h>
    
     // when stackExample is called, arg is allocated on the stack
     void stackExample(int arg) {
         int a = 10; // Variable 'a' is allocated on the stack
         printf("Stack Variable: %d, %d\n", a, arg);
     }
    
     int main() {
         stackExample(20);
         return 0;
     }
    

    In this example, the variables a and arg are allocated on the stack inside the stackExample function. The memory for a and arg is automatically released when the function returns.

  2. Heap Allocation: Heap memory is used for dynamic memory allocation, and it must be managed manually at runtime. The functions malloc, calloc, and realloc are used to allocate memory on the heap, and free is used to deallocate memory.

     #include <stdio.h>
     #include <stdlib.h>
    
     void heapExample() {
         int *b = (int *)malloc(sizeof(int)); // Allocate memory on the heap
         if (b == NULL) {
             fprintf(stderr, "Memory allocation failed\n");
             return;
         }
    
         *b = 20; // Assign a value to the heap-allocated variable
         printf("Heap Variable: %d\n", *b);
    
         free(b); // Deallocate memory when done
     }
    
     int main() {
         heapExample();
         return 0;
     }
    

    In this example, memory for the pointer variable b is allocated on the stack but the address it contains belongs to the heap, and that area of memory is allocated dynamically by using malloc. It's important to free the allocated memory using free to avoid memory leaks.

    Remember that stack memory is managed automatically, and its size is typically limited. On the other hand, heap memory needs to be explicitly managed, but it provides more flexibility and can be used for dynamic data structures.

Note: In modern C, it's common to use calloc instead of malloc for allocating memory, as it initializes the allocated memory to zero. Also, be cautious when using pointers and dynamic memory allocation to avoid memory leaks and undefined behavior.