Home > Software design >  Why local variables have undetermined values in C if not initialized?
Why local variables have undetermined values in C if not initialized?

Time:11-14

In C - Linux OS, when a function is called the epilogue portion of Assembly creates a stack frame and the local variables are in reference to base pointers. My question is that what makes the variable hold undetermined values when we print the variable without initializing. My theory is that when we make use of the variable, the OS brings the page corresponding to the local variable's address and the address in that page may have some value that makes the value of the local variable. Is that correct?

CodePudding user response:

Let's look at the disassembly of a simple program:

#include <stdio.h>

int main() {
    unsigned int i;
    unsigned int j = 1;
    printf("%u\n", j);
    printf("%u\n", i);
}

The disassembly, with GCC-11.1 on default optimisation is:

    .file   "char.c"
    .text
    .section    .rodata
.LC0:
    .string "%u\n"
    .text
    .globl  main
    .type   main, @function
/*So, till here is meta data and other stuff. We're interested in what's bottom*/

main:
.LFB0:
    .cfi_startproc
    endbr64
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $16, %rsp
    movl    $1, -8(%rbp)
    movl    -8(%rbp),            
  • Related