Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler init this variable to the wrong value? Is this an alignment issue?

I'm working with an embedded C compiler (ARM cortex-m3 chip) and it seems to initialize the wrong value to a struct. Why does this happen? If it's an alignment issue, shouldn't the compiler know to align an int32u to a 4-byte boundary?

Note: the printf merely throws bytes out of the serial port. There is no stdio.h implementation on this chip.

typedef struct
{
    int32u startTime; 
    int16u length;
    int32u offTime;
} Cycle;

Cycle cycle = 
{
    315618000, 
    1200,
    0
};


void init()
{
   printf("\r\nInitialized! Cycle Start: %d", cycle.startTime);

   cycle.startTime = 315618000;
   cycle.length = 1200;

   printf(" Cycle Start: %d", cycle.startTime);

}

Output: Initialized! Cycle Start: 631237200 Cycle Start: 315618000

Note:: This NOT a printf issue. The debugger verifies the value in memory as 631237200 as well.

like image 570
MandoMando Avatar asked Nov 02 '22 16:11

MandoMando


1 Answers

In some embedded systems, static initialization is not set up to happen automatically. This goes against C specifications, but sometimes that's the way it is. Note that this may be true for both data and bss segments i.e. you may find that uninitialized statics may NOT be initialized to zero either.

The solution to this is, unfortunately, system specific. You may find something in your complier system documentation that lets you invoke the initialization of the static elements.

like image 164
Ziffusion Avatar answered Nov 10 '22 02:11

Ziffusion