Local variable initialized to zero in C

I thought the local variable in C was not initialized. But when I compiled this code with gcc.

void f() {
    static int s;
    int n;

    printf("static s = %d\n", s++);
    printf("local  n = %d\n", n++);

    f();
}

main() {
    f();
}

And run this code, partial result:

static s = 0
local  n = 0
static s = 1
local  n = 0
static s = 2
local  n = 0
static s = 3
local  n = 0
static s = 4
local  n = 0
static s = 5
local  n = 0
...
static s = 261974
local  n = 0
static s = 261975
local  n = 0
static s = 261976
local  n = 0
static s = 261977
local  n = 0
static s = 261978
local  n = 0
static s = 261979
local  n = 0
static s = 261980
local  n = 0
static s = 261981
local  n = 0
Segmentation fault: 11

Can anyone explain this? Or refer to the standard link that C will not trigger local vars?

+4
source share
7 answers

ISO / IEC 9899: TC3 WG14 / N1256 (C99 standard) clause 6.7.8 clause 10:

If an object with automatic storage duration is not initialized explicitly, its value is undefined.

If an object that has a static storage duration is not initialized explicitly, then:

  • if it has a pointer type, it is initialized with a null pointer;
  • , ( );
  • , () ;
  • , () .

. , ( 0). , , , , . .

+8

, 0 , .

+2

static , , .

0 , . 42 -12345.

. , , . undefined, , - .

- :

int n = 0;

(, #include <stdio.h>, main - int main(void).)

+2

, , undefined ( , ). , , . . . , ( "" , ), n . .

+1

, . , 0.

0

; , .

-1

, , ( , ) . , . , , , .. GARBAGE, , .

f() , ( ).

-1

All Articles