Fandom

lwIP Wiki

Why are global variables not initialized to zero?

91pages on
this wiki
Add New Page
Talk1 Share

We often get asked why we don't explicitly initialize global variables to zero or NULL (no matter whether they are static or exported). There are two reasons for this:

  1. Not initializing them saves program space: every initialized variable has to be put into the compiled binary and the loader normally just copies the initialization values to the runtime variable storage by memcpy'ing a whole section (e.g. from flash to ram). This is also true for variables initialized to zero or NULL!
  2. There's no need to initialize them, as the C standard requires global, uninitialized variables to be implicitly initialized to zero or NULL (no matter whether they are static or exported).(*) See below for an excerpt of the relevant portions of the standard.


Q: But my global variables aren't initialized to zero!

A: Well, then your compiler (or rather your loader, which normally is responsible of zeroing the relevant section) doesn't conform to the C standard. This has been mostly observed for hand-written startup code where zeroing the relevant section (e.g. named '.bss' for gcc) has been forgotten (or deliberately omitted). If your intention was not having to initialize the whole ram, then put variables you know don't need to be initialized in a dedicated section 'uninitialized'.

Note: If you want to speed up lwIP startup, the heap (from mem.c) and the pools (from memp.c) can be left uninitialized.


Relevant sections of the C standard (found on the web):

3.1.2.4 Storage durations of objects

   An object declared with external or internal linkage, or with the
storage-class specifier static has static storage duration.  For such
an object, storage is reserved and its stored value is initialized
only once, prior to program startup.  The object exists and retains
its last-stored value throughout the execution of the entire
program.

3.5.7 Initialization

   If an object that has static storage duration is not initialized
explicitly, it is initialized implicitly as if every member that has
arithmetic type were assigned 0 and every member that has pointer type
were assigned a null pointer constant.

(*) Well, in detail, it requires to do so on variables with 'static storage', but that's not what the C keyword 'static' means. Instead, it rather translates to 'global variables' as opposed to 'local variables' or struct members.

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.