555
555

Reputation: 1

Why does struct memory initalize with random characters? (Embedded)

Using MCUXpresso with NXP MKL02Z16VFM4 for reference.

When I declare a struct like so

typedef struct {
        uint8_t DATA :8;
} myStruct;
myStruct xxx __attribute__ ((section ("xyz")));

the position in memory is filled with random characters. The processor is little endian so when I try to access this address, I get those random characters and the data I have written to the struct.

//At address 0x1FFFFE84 : BD84D1E4

xxx.DATA = 0xAA; //Assign some numbers to struct

//Now, 0x1FFFFE84 : BD84D1AA

I can use memset to clear the memory, but I'd like to know why the memory is filled with these random characters when declaring a struct.

Upvotes: 0

Views: 57

Answers (2)

Roberto Caboni
Roberto Caboni

Reputation: 7490

A struct variable, but actually ANY variable, needs to be initialized before being used in the code. Accessing (reading) uninitialized data causes undefined behavior, meaning that there's not guarancy that the compiler will behave in a predictable way.

Most compilers set to 0uninitialized variables, but some other compilers (some embedded compilers, for example) don't. And that's why you see random values.

Upvotes: 0

Clifford
Clifford

Reputation: 93556

You have explicitly located xxx in section xyz - this section is unknown to the compiler and the default start-up code, so need not be explicitly zero initialised as the default bss segment would be. For most volatile memory technologies, memory has non-deterministic content at power up - hence apparently random in this case.

If you expect zero initialisation of private sections, you need to explicitly add that in your linker script and/or start-up code. The content of the unused memory surrounding the struct or any alignment padding within it however is irrelevant and explicitly clearing it to some known value is largely unnecessary.

Upvotes: 3

Related Questions