Background I am working on an embedded application written in C using IAR Embedded Workbench IDE and toolchain which runs on an STM32F091 (ARM Cortex-M0 core) microcontroller. The application writes data to the microcontrollers embedded flash memory, into which only 32-bit words can be entered (perhaps half-words work also).
Problem description The data is stored in an uint8_t byte type array preceeded by some header information at the start (in this case an AT response code from an on-board modem) which should not be written to flash. I'd like to send a uint32_t pointer to to where in the uint8_t buffer the actual data starts. But if this offset is not 4 byte aligned, my application crashes since it tries to access an unaligned uint32_t type.
This describes what I'm trying to do (not the real code, just an example):
uint8_t modemResponseBuffer[MAX_MODEM_RESPONSE_SIZE];
/* Get the modem response data (including modem response header data) */
size_t modemResponseSize = GetModemResponseData(modemResponseBuffer);
/* Get the actual data size from the header information */
size_t dataSize = GetActualDataSizeFromModemResponseHeader(modemResponseBuffer);
/* Get the offset to where the actual data starts in the modem response */
size_t modemDataOffset = GetModemResponseDataOffset(modemResponseBuffer);
/* Write the data part of the response to embedded flash memory.
The modemDataOffset can be any number which messes up 4 byte data alignment */
ProgramFlashMemory(DATA_FLASH_STORAGE_ADDRESS, (uint32_t*)&modemResponseBuffer[modemDataoffset],
dataSize);
Inside the ProgramFlashMemory function, the FLASH_ProgramWord Standard Peripheral Library function is called in a loop.
Question(s) How do I solve this problem efficiently? I'm working on a system where I have limited amount of memory (32 kb RAM), so I would prefer not to copy the desired contents from the uint8_t buffer to a new buffer of uint32_t type. At the moment I've manually aligned the data byte by byte by looping through, but this seems rather clumsy to me. But I've yet to come up with a better solution and I am interested in what suggestions I might receive here.
Also, if someone has the knowledge, I also wonder why the application crashes in this case. What is the reason my core (or any core?) can't handle unaligned data types?