Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, why does my initialized to 0 int variable get reported as uninitialized by "nm"?

I have the following C code:

   //declared at the beginning of the CAStar.c file:
    int TERRAIN_PASSABLE = 1;
    int TERRAIN_IMPASSABLE = 0;
    int TERRAIN_SOME_WHAT_PASSABLE = 2;

I've noticed that for any of these variables, if they have a non-zero value, they are reported by the "nm" command as type "D" (initialized):

_TERRAIN_PASSABLE          |00000008|   D  |
_TERRAIN_SOME_WHAT_PASSABLE|00000004|   D  |

However, those initialized to 0 are reported as "B" (uninitialized):

_TERRAIN_IMPASSABLE        |00000000|   B  |

Why the difference between "initialized with 0" and "initialized with something else but 0" ?

like image 998
Shivan Dragon Avatar asked Dec 10 '13 10:12

Shivan Dragon


People also ask

Why do we initialize variables to 0 in C?

Declaring variables without initialization lead to logical errors which are hard to debug sometimes. So to avoid this, we write it like this int sum = 0; We declared variable 'sum' and initializated it to 0 to avoid any error.

Is an int initialized to 0?

No difference - int members are initialized to zero by default.

Is an uninitialized variable null in C?

In C, variables with static storage duration that are not initialized explicitly are initialized to zero (or null, for pointers).

Which variables are automatically initialized to zero?

Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code. These variables are allocated in .


1 Answers

This is more or less about how BSS works and how it is used. B means that variable will be placed in BSS section (and you are right it is uninitialized data section). D means that the symbol is placed in initialized data section.

Read for example this article to know bit more about how BSS works and what it is used for.

like image 110
codewarrior Avatar answered Nov 16 '22 04:11

codewarrior