Computing > Programming

malloc to struct pointer = hard fault. What am I doing wrong?

<< < (4/4)

SiliconWizard:

--- Quote from: DavidAlfa on August 26, 2021, 04:32:36 pm ---I've tested that in the past, might depend on being Big or small endian?
In stm32, putting the smaller first is what saves space.

--- End quote ---

I suppose you're replying to the idea of ordering struct members to minimize padding?
I don't see how endianness could play any role here? And anyway, almost all common targets these days are little endian.

The reason for what Nominal Animal said is simple. It's akin to filling a container with stones of various sizes. You'll get the most stones in if you fill it with the bigger ones first. The smaller ones will then be able to get through. Not sure this image fits the problem completely, but I like it.

A small example, let's imagine you have 4 struct members like this:

--- Code: ---uint32_t n1;
uint8_t n2;
uint16_t n3;
uint32_t n4;

--- End code ---

Let's assume a 32-bit integer must be 32-bit aligned, a 16-bit integer 16-bit aligned, and 8-bit integer 8-bit aligned.
Ordered in the above way, the offsets will be the following:
n1: 0
n2: 4
n3: 6
n4: 8
=> struct size = 12 bytes

Now let's reorder with the larger alignments first:

--- Code: ---uint32_t n1;
uint32_t n4;
uint16_t n3;
uint8_t n2;

--- End code ---

The offsets will now be the following:
n1: 0
n4: 4
n3: 8
n2: 10
=> struct size = 11 bytes

Now let's reorder with the smaller alignments first:

--- Code: ---uint8_t n2;
uint16_t n3;
uint32_t n1;
uint32_t n4;

--- End code ---

The offsets will now be the following:
n2: 0
n3: 2
n1: 4
n4: 8
=> struct size = 12 bytes

The larger the number of members, the larger the size difference will be.

Navigation

[0] Message Index

[*] Previous page

There was an error while thanking
Thanking...
Go to full version