Variables storage

Simple explanation

When a variable is declared, the process will reserve a certain amount of memory on the stack to store the value of the variable. The process will allocate enough memory to hold the entire possible value. For example, if you declare a string with size 20, the process will allocate 20 bytes of memory on the stack for that string.

If no value is initialized, the initial value of the variable will be undefined. This means that it may have any value, and that value may be different each time the program is executed.

When a value is assigned to a variable, the compiler will store that value at the memory address associated with the variable.

Code example

#include <stdio.h>
#include <string.h>

int main(void) {
  char string1[16]; // create an array of characters with size 16
  char string2[16]; // create a second array of characters with size 16

  printf("string1 stack address : %p\n", string1);
  printf("string2 stack address : %p\n", string2);

  printf("%s\n", string1);
  printf("%s\n", string2);

  // fill the first string with 15 'A's followed by a null character '\0'
  memset(string1, 'A', 15);
  string1[15] = '\0';

  // fill the second string with 15 'B's followed by a null character '\0'
  memset(string2, 'B', 15);
  string2[15] = '\0';

  printf("String 1: %s\n", string1); // print string 1
  printf("String 2: %s\n", string2); // print string 2

  return 0;
}

This code will declare two arrays of characters, string1 and string2, and set them with the strings "AAAAAAAAAAAAAAA" and "BBBBBBBBBBBBBBB", respectively.

The output of this program would be :

This code provides a basic example of how variables are treated on the stack in C.

Stack representation

When the string1 variable is declared, the process reserve 16 byte onto the stack to store this variable :

Note that values on the stack aren't initialized to any specific value. If there is already some data in the memory space allocated to the variable, this data will remain until it is overwritten by a new value.

When the string2 variable is declared, the process reserve 16 byte onto the stack to store this variable

The variable string2 is stored above the string1 variable due to LIFO system

Then, the process will do a memset() to each variable to set "A" and "B" 15 times respectively into string1 and string2 and then put a null byte 0x00 at the end of the string

string1 contains 15 0x41 wich is the hex value of A following by a null byte 0x00

string2 contains 15 0x42 wich is the hex value of B following by a null byte 0x00

Last updated