I am trying to find a better title so I apologize if its confusing.
I have a binary message that I am reading over a serial port. The message contains a constant 8 byte header, and a dynamic message length (depends on the message type which is defined in the 8 byte header).
I am trying to create a function that returns this message with the array allocated using malloc.
I changed some of the variable/member names just to make it clearer Example:
#include <stdlib.h>
#include <stdio.h>
typedef struct MyMessageHeader {
uint8_t byte1, byte2, byte3, byte4, byte5, byte6, byte7,
} MyMessageHeader;
// I could have up to 100 different message types, but they all contain
// the same header, so trying to make a message type with a header and array pointer
typedef struct MyMessage {
MyMessageHeader header;
uint8_t* data;
} MyMessage;
// Function to copy a raw byte array that is read from the serial port into
// a MyMessage object
MyMessage* FunctionThatIsNotWorking(uint8_t* rawBytes) {
// Somehow we have determined in rawBytes that this message contains 12 bytes of data
// plus the 8 bytes which is the header
MyMessage* ret_msg = malloc(20);
// This is where things go wrong and I get segmentation faults. Likely due to
// my misunderstanding of malloc.
// Copy the rawBytes into MyMessage. Assuming the first 8 bytes of rawBytes goes
// into MyMessageHeader, and the last 12 bytes go into data
memcpy(ret_msg, rawBytes, 20);
}
int main() {
uint8_t raw_bytes[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
MyMessage* my_msg = FunctionThatIsNotWorking(raw_bytes);
// Expecting now but this doesnt work
my_msg->header.byte1 == 1;
my_msg->header.byte2 == 2;
my_msg->header.byte3 == 3;
// ...
// first byte of data should be the 9th byte in raw_bytes
my_msg->data[0] == 9;
my_msg->data[1] == 10;
}
What am I missing here, or what is my mis-understanding?
uint8_t raw_bytes[20] = {...}) IS a legitimate "mock" for a "real" input stream of bytes. I believe the actual problem is that his struct layout doesn't necessarily match the raw byte stream. Because of structure padding. Hence a naive "memcpy" will fail :(raw_bytes[]will absolutely not be valid bytewise representation for astruct MyMessage. Look again.