Why variables start with random values ​​in C

I think this is wrong, it should start as NULL, and not with a random value. In case you have a pointer with a random memory address as the default, this can be very dangerous, no?

+3
source share
7 answers

No. C is a very effective language that has traditionally been faster than many other languages. One reason for this is that he does not do too much for this. The programmer controls it.

In the case of initialization, the C variables are not initialized with a random value. Rather, they are not initialized and therefore they contain everything that was in the memory cell before.

If you want to initialize a variable, say, 1 in your program, then it will be ineffective if the variable has already been initialized to zero or zero. This would mean that it was initialized twice.

+3
source

Variables start uninitialized because this is the fastest way - why waste CPU cycles on initialization if you are going to write a different value anyway?

If you want the variable to be initialized after creation, just initialize it. :)

, : , .

+5

( ). C , , , , .

, static, 0.

+2

, , . , . - , , , ?

+1

- , , C .

+1

" C " . -

void foo()
{
    struct bar *ptrs[10000];
    /* do something where only a few indices end up actually getting used */
}

, , , , , , , , .

, malloc. .

, , {0} calloc.

+1

, , , .

( ) 0, - , . , , (locals), , -, , .

C , , , , , , ( ).

, C-, , "" (, 0 NULL). , , , .

, . , locals , (, ). , . , , , , test/debug.

Typically, this compiler behavior is enabled only for debug builds; I could see that the argument was made to include it in release builds, especially if the release build can still optimize it when the compiler can prove that the implicit initialized value is never used.

0
source

Source: https://habr.com/ru/post/1780128/


All Articles