BGLIB SiliconLabs code bug? - c

I'm using the SiliconLabs's BGLIB static library for comunicate via SerialPort, with BLED112.
For use this library it's necessary to define two function: one for send and another for receive bytes to and from SerialPort. All data received from serial can be divided in two part: header and data.
Following the "main.c" code of "thermometer-demo" example the function that receive data from serial, receive first of all header and than data. When the header and data has been received, the code parse the header by follow code and initialize a *msg variable:
unsigned char data[256];
struct ble_header hdr;
int r;
r = uart_rx(sizeof(hdr), (unsigned char *)&hdr, UART_TIMEOUT);
.
.
.
if (hdr.lolen) {
r = uart_rx(hdr.lolen, data, UART_TIMEOUT);
.
.
.
}
const struct ble_msg *msg = ble_get_msg_hdr(hdr);
The *msg variable is a ble_msg struct pointer and this struct is so defined:
struct ble_msg
{
struct ble_header hdr;
uint32 params;
ble_cmd_handler handler;
};
handler is a function pointer that is initialized when *msg is inizialized. After parse header the code call this function pointer:
The functions used to initialize this function pointer are defined empty from the library and if you want to use one of this, it's necessary to delete it and rewrite.
In the "thermometer-demo" example is used void ble_evt_gap_scan_response(const struct ble_msg_gap_scan_response_evt_t *msg) function to receive all visibled devices and the ble_msg_gap_scan_response_evt_t are so defined:
PACKSTRUCT(struct ble_msg_gap_scan_response_evt_t
{
int8 rssi;
uint8 packet_type;
bd_addr sender;
uint8 address_type;
uint8 bond;
uint8array data;
});
with uint8array so defined:
typedef struct
{
uint8 len;
uint8 *data;
}uint8array;
Here for me there is the problem: when the msg->handler(data) code is executed and than the ble_evt_gap_scan_response function is called, a cast is executed between data buffer and ble_msg_gap_scan_response_evt_t struct and the content of uint8 *data (in uint8array struct) is initialized with data received from SerialPort and than, will point to a non correct RAM location.
I think the intention is to provide a way to have a directly access to the data but for me is not the correct way.
It's my wrong evaluation or is a bglib bug?

I have contacted SiliconLabs support and that the original libraries are correct and it seem I have a incorrect version of the libraries.
Like the SiliconLabs support suggest me (and like explained very good in this link: http://www.drdobbs.com/questions-answers-creating-variable-siz/184403480), there are 3 possible kind of declarations:
1° declaration:
typedef struct
{
uint8 len;
uint8 data[0];
}uint8array;
and I access to data with:
msg->data->data[0]
msg->data->data[1]
msg->data->data[2]
...
msg->data->data[n]
In this case could happen compiler warns that the buffer index exceeds the limits.
2° declaration:
typedef struct
{
uint8 len;
uint8 data[1000];
}uint8array;
In this case it's possible to access to data in the same way as previous one but or more space has been allocaded than necessary (in embedded sometime it's important optimize because the resources are limited) or, like previous, you could exceed the buffer limits.
3° declaration:
typedef struct
{
uint8 len;
uint8 data[];
}uint8array;
The name of this declaration is Flexible array member (https://en.wikipedia.org/wiki/Flexible_array_member) and are introduced in the C99 standard. In this case it's possible to access to data in the same way as previouses one but the compiler can warns that isn't a standard declaration.
This declaration is the same adopted by SiliconLabs for the library.
In my case I'm using VisualStudio and I have adopted the third solution but compiler return me the warning C4200 (non standard declaration). I tried the first solution and compiler doesn't return me no warns but for me, the clarity of code is missing and could be a problem for future uses.

Related

Pointer to Union of Structs

I'm working with an USART device that send to my MCU a series of different commands (also different is size) and I want to try the best way to parse the commands.
I defined two packed structure (one for each command)
typedef ccport_PACKED( struct TASK_CommandStandard
{
UINT8 startByte;
UINT16 length;
UINT8 command;
UINT16 crc16;
}) TASK_CommandStandard_t;
typedef ccport_PACKED( struct TASK_CommandExitBootloader
{
UINT8 startByte;
UINT16 length;
UINT8 command;
UINT8 reserved;
UINT16 crc16;
}) TASK_CommandExitBootloader_t;
and one Union:
typedef union TASK_Command
{
TASK_CommandStandard_t standard;
TASK_CommandExitBootloader_t exitbootloader;
} TASK_Command_t;
My application receives the USART command inside a UINT8 buffer and after that, looking into the 4th byte I can detect the type of the command (standard or exitbootloader).
To parse the command, my idea is to use one pointer TASK_Command_t *newCommand and based on the command code, assign the address of instance.rxFrameBuffer to:
newCommand->exitbootloader = (TASK_CommandExitBootloader_t *)instance.rxFrameBuffer
or
newCommand->standard = (TASK_CommandStandard_t *)instance.rxFrameBuffer
This is my function:
static void TASK_FSM_FrameReceived( void )
{
UINT8 commandCode;
TASK_Command_t *newCommand;
commandCode = instance.rxFrameBuffer[TASK_COMMAND_CODE_INDEX];
if( commandCode == TASK_COMMAND_CODE_EXIT_BOOTLOADER )
{
newCommand->exitbootloader = (TASK_CommandExitBootloader_t *)instance.rxFrameBuffer;
}
else
{
newCommand->standard = (TASK_CommandStandard_t *)instance.rxFrameBuffer;
}
......
}
Unfortunately, the compiler returns this error:
incompatible types when assigning to type 'TASK_CommandExitBootloader_t' {aka 'struct TASK_CommandExitBootloader'} from type 'TASK_CommandExitBootloader_t *' {aka 'struct TASK_CommandExitBootloader *'}
Can someone give me a hint?
newCommand->exitbootloader isn't a pointer, it's a struct, thus if you want to copy data of instance.rxFrameBuffer to this struct, you need to use memcpy, or union. You could also dereference like so *((TASK_CommandExitBootloader_t *)instance.rxFrameBuffer) however this may be undefined behaviour depending the type of rxFrameBuffer, so I don't recommend it.
newCommand is an uninitialized pointer so it can't be used until you point at valid memory somewhere. The code will crash & burn when you attempt newCommand->exitbootloader.
You can't just wildly point into an UART rx buffer and merrily be on your way. Where is this data coming from, interrupts or DMA? How do you handle re-entrancy? Where are the actual volatile qualifier registers and how did you get the data from there?
Strict aliasing is real and it is nasty, particularly if using gcc. So you can't point into a pre-declared uint8_t array buffer for that reason. You can cast between those two different struct types if the union containing them both is present, but better to avoid all such conversions.
I'd also strongly recommend dropping "my local garage standard" types UINT8 or whatever in favour for internationally standardized, well-known C standard types uint8_t etc from stdint.h.
Also regarding hard copy of raw UART buffers on low-end microcontroller systems, that's a very common beginner mistake. See this answer for an example of how to do it properly.
I had to do something similar (pointer to raw data to save memory)
I did something like this :
typedef struct TASK_CommandStandard
{
volatile UINT8 startByte;
volatile UINT16 length;
volatile UINT8 command;
volatile UINT16 crc16;
} TASK_CommandStandard_t;
typedef struct TASK_CommandExitBootloader
{
volatile UINT8 startByte;
volatile UINT16 length;
volatile UINT8 command;
volatile UINT8 reserved;
volatile UINT16 crc16;
} TASK_CommandExitBootloader_t;
#define USART_Foo_Address 0x0F00000
#define USART_cmd ((TASK_CommandStandard_t*) USART_Foo_Address)
#define USART_exit ((TASK_CommandExitBootloader_t*) USART_Foo_Address)
Don't forget to check padding/alignment, it was working fine on my MCU
You use it like this :
static void TASK_FSM_FrameReceived( void )
{
if( instance.rxFrameBuffer[TASK_COMMAND_CODE_INDEX] == TASK_COMMAND_CODE_EXIT_BOOTLOADER )
{
USART_exit->length;
....
}
else
{
USART_cmd->length;
....
}
......
}
I solved modifing the union:
typedef union TASK_Command
{
TASK_CommandStandard_t *standard;
TASK_CommandExitBootloader_t *exitbootloader;
} TASK_Command_t;
and in my function insted using a
TASK_Command_t *newCommand;
I used
TASK_Command_t newCommand;
In this way I can use the same variable to cast my different messages without make any buffer copy.
I can access to the UART buffer with
newCommand.standard = (TASK_CommandStandard_t *)instance.rxFrameBuffer;

Initializing a const array inside a struct

#define LENGTH 6
typedef char data_t[LENGTH];
struct foo {
const data_t data;
...
}
...
void bar(data_t data) {
printf("%.6s\n", data);
struct foo myfoo = {*data};
printf("%.6s\n", foo.data);
}
I'm trying to have this struct which holds directly the data I'm interested in, sizeof(foo) == 6+the rest, not sizeof(foo) == sizeof(void*)+the rest. However I can't find a way to initialize a struct of type foo with a data_t. I think maybe I could remove the const modifier from the field and use memcpy but I like the extra safety and clarity.
I don't get any compile errors but when I run the code I get
123456
1??
so the copy didn't work properly I think.
This is for an arduino (or similar device) so I'm trying to keep it to very portable code.
Is it just not possible ?
EDIT: removing the const modifier on the data_t field doesn't seem to help.
It is possible to do this, for some cost >=0.
typedef struct
{
char c[LENGTH];
} data_t; // this struct is freely copyable
struct foo
{
const data_t data; // but this data member is not
int what;
};
void foo (char* x) {
data_t d; // declare freely copyable struct instance
memcpy(d.c, x, sizeof(d.c)); // memcpy it
struct foo foo = { d, 42 }; // initialise struct instance with const member
...
};
Some compilers (e.g. clang) are even able to optimise away the redundant copying (from x to d.c and then from d to foo.data ⇒ from x straight to foo.data). Others (gcc I'm looking at you) don't seem to be able to achieve this.
If you pass around pointers to data_t rather than straight char pointers, you won't need this additional memcpy step. OTOH in order to access the char array inside foo you need another level of member access (.data.c instead of just .data; this has no runtime cost though).
It's impossible to do it in a standard compliant way.
Due to its being const, const char data[6]; must be initialized to be usable, and it may only be initialized statically (static objects with no initializer get automatically zeroed), with a string literal, or with a brace-enclosed initializer list. You cannot initialize it with a pointer or another array.
If I were you, I would get rid of the const, document that .data shouldn't be changed post-initialization, and then use memcpy to initialize it.
(const on struct members doesn't work very well in my opinion. It effectively prevents you from being able to have initializer functions, and while C++ gets around the problem a little bit by having special language support for its constructor functions, the problem still remains if the const members are arrays).

Data encapsulation in C

I am currently working on an embedded system and I have a component on a board which appears two times. I would like to have one .c and one .h file for the component.
I have the following code:
typedef struct {
uint32_t pin_reset;
uint32_t pin_drdy;
uint32_t pin_start;
volatile avr32_spi_t *spi_module;
uint8_t cs_id;
} ads1248_options_t;
Those are all hardware settings. I create two instances of this struct (one for each part).
Now I need to keep an array of values in the background. E.g. I can read values from that device every second and I want to keep the last 100 values. I would like this data to be non-accessible from the "outside" of my component (only through special functions in my component).
I am unsure on how to proceed here. Do I really need to make the array part of my struct? What I thought of would be to do the following:
int32_t *adc_values; // <-- Add this to struct
int32_t *adc_value_buffer = malloc(sizeof(int32_t) * 100); // <-- Call in initialize function, this will never be freed on purpose
Yet, I will then be able to access my int32_t pointer from everywhere in my code (also from outside my component) which I do not like.
Is this the only way to do it? Do you know of a better way?
Thanks.
For the specific case of writing hardware drivers for a microcontroller, which this appears to be, please consider doing like this.
Otherwise, use opaque/incomplete type. You'd be surprised to learn how shockingly few C programmers there are who know how to actually implement 100% private encapsulation of custom types. This is why there's some persistent myth about C lacking the OO feature known as private encapsulation. This myth originates from lack of C knowledge and nothing else.
This is how it goes:
ads1248.h
typedef struct ads1248_options_t ads1248_options_t; // incomplete/opaque type
ads1248_options_t* ads1248_init (parameters); // a "constructor"
void ads1248_destroy (ads1248_options_t* ads); // a "destructor"
ads1248.c
#include "ads1248.h"
struct ads1248_options_t {
uint32_t pin_reset;
uint32_t pin_drdy;
uint32_t pin_start;
volatile avr32_spi_t *spi_module;
uint8_t cs_id;
};
ads1248_options_t* ads1248_init (parameters)
{
ads1248_options_t* ads = malloc(sizeof(ads1248_options_t));
// do things with ads based on parameters
return ads;
}
void ads1248_destroy (ads1248_options_t* ads)
{
free(ads);
}
main.c
#include "ads1248.h"
int main()
{
ads1248_options_t* ads = ads1248_init(parameters);
...
ads1248_destroy(ads);
}
Now the code in main cannot access any of the struct members, all members are 100% private. It can only create a pointer to a struct object, not an instance of it. Works exactly like abstract base classes in C++, if you are familiar with that. The only difference is that you'll have to call the init/destroy functions manually, rather than using true constructors/destructors.
It's common that structures in C are defined completely in the header, although they're totally opaque (FILE, for example), or only have some of their fields specified in the documentation.
C lacks private to prevent accidental access, but I consider this a minor problem: If a field isn't mentioned in the spec, why should someone try to access it? Have you ever accidentally accessed a member of a FILE? (It's probably better not to do things like having a published member foo and a non-published fooo which can easily be accessed by a small typo.) Some use conventions like giving them "unusual" names, for example, having a trailing underscore on private members.
Another way is the PIMPL idiom: Forward-declare the structure as an incomplete type and provide the complete declaration in the implementation file only. This may complicate debugging, and may have performance penalties due to less possibilities for inlining and an additional indirection, though this may be solvable with link-time optimization. A combination of both is also possible, declaring the public fields in the header along with a pointer to an incomplete structure type holding the private fields.
I would like this data to be non-accessible from the "outside" of my
component (only through special functions in my component).
You can do it in this way (a big malloc including the data):
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct {
uint32_t pin_reset;
uint32_t pin_drdy;
uint32_t pin_start;
volatile avr32_spi_t *spi_module;
uint8_t cs_id;
} ads1248_options_t;
void fn(ads1248_options_t *x)
{
int32_t *values = (int32_t *)(x + 1);
/* values are not accesible via a member of the struct */
values[0] = 10;
printf("%d\n", values[0]);
}
int main(void)
{
ads1248_options_t *x = malloc(sizeof(*x) + (sizeof(int32_t) * 100));
fn(x);
free(x);
return 0;
}
You could make a portion of your structure private like this.
object.h
struct object_public {
uint32_t public_item1;
uint32_t public_item2;
};
object.c
struct object {
struct object_public public;
uint32_t private_item1;
uint32_t *private_ptr;
}
A pointer to an object can be cast to a pointer to object_public because object_public is the first item in struct object. So the code outside of object.c will reference the object through a pointer to object_public. While the code within object.c references the object through a pointer to object. Only the code within object.c will know about the private members.
The program should not define or allocate an instance object_public because that instance won't have the private stuff appended to it.
The technique of including a struct as the first item in another struct is really a way for implementing single inheritance in C. I don't recall ever using it like this for encapsulation. But I thought I would throw the idea out there.
You can:
Make your whole ads1248_options_t an opaque type (as already discussed in other answers)
Make just the adc_values member an opaque type, like:
// in the header(.h)
typedef struct adc_values adc_values_t;
// in the code (.c)
struct adc_values {
int32_t *values;
};
Have a static array of array of values "parallel" to your ads1248_options_t and provide functions to access them. Like:
// in the header (.h)
int32_t get_adc_value(int id, int value_idx);
// in the code (.c)
static int32_t values[MAX_ADS][MAX_VALUES];
// or
static int32_t *values[MAX_ADS]; // malloc()-ate members somewhere
int32_t get_adc_value(int id, int value_idx) {
return values[id][value_idx]
}
If the user doesn't know the index to use, keep an index (id) in your ads1248_options_t.
Instead of a static array, you may provide some other way of allocating the value arrays "in parallel", but, again, need a way to identify which array belongs to which ADC, where its id is the simplest solution.

Public sizeof for privately defined struct

I have a little data-hiding module that looks like this:
/** mydata.h */
struct _mystruct_t;
typedef struct _mystruct_t mystruct;
mystruct *newMystruct();
void freeMystruct( mystruct** p );
/** mydata.c */
#include "mydata.h"
struct _mystruct_t {
int64_t data1;
int16_t data2;
int16_t data3;
};
// ... related definitions ... //
For the most part, this is what I want; although simple, the struct has strict consistency requirements and I really don't want to provide access to the data members.
The problem is that in client code I would like to include the struct in another struct which I would like to allocate on the stack. Right now I am jumping through hoops to free the mystruct*s in some client code. Since a) mystruct is pretty small and I really don't think it's going to get big anytime soon and b) it's not a problem that client code has to recompile if I ever change mystruct, I would like to make the size of mystruct public (i.e. in the header).
Two possibilities I've considered:
/** mydata.h */
typedef struct {
// SERIOUSLY DON'T ACCESS THESE MEMBERS
int64_t data1;
int16_t data2;
int16_t data3;
} mystruct;
I think the drawbacks here speak for themselves.
OR
/** mydata.h */
#define SIZEOF_MYSTRUCT (sizeof(int64_t)+sizeof(int16_t)+sizeof(int16_t))
// everything else same as before...
/** mydata.c */
// same as before...
_Static_assert (SIZEOF_MYSTRUCT == sizeof(mystruct), "SIZEOF_MYSTRUCT is incorrect")
Of course this seems non-ideal since I have to update this value manually and I don't know if/how alignment of the struct could actually cause this to be incorrect (I thought of the static assert while writing this question, it partially addresses this concern).
Is one of these preferred? Or even better, is there some clever trick to provide the actual struct definition in the header while later somehow hiding the ability to access the members?
You can create different .h file distributed to the end user that would define your secret structure just as byte array (you can't hide data without crypto/checksumming more than just saying "here are some bytes"):
typedef struct {
unsigned char data[12];
} your_struct;
You just have to make sure that both structures are the same for all the compilers and options, thus using __declspec(align()) (for VC) in your library code, so for example:
// Client side
__declspec(align(32)) typedef struct {
int64_t data1;
int16_t data2;
int16_t data3;
} mystruct;
To prevent structure from being 16B long instead of commonly expected 12B. Or just use /Zp compiler option.
I would stay with a configure time generated #define describing the size of the mystruct and possibly a typedef char[SIZEOF_MYSTRUCT] opaque_mystruct to simplify creation of placeholders for mystruct.
Likely the idea of configure time actions deserves some explanations. The general idea is to
place the definition of the mystruct into a private, non-exported but nevertheless distributed header,
create a small test application being built and executed before the library. The test application would #include the private header, and print actual sizeof (mystruct) for a given compiler and compile options
create an appropriate script which would create a library config.h with #define SIZEOF_MYSTRUCT <calculated_number> and possibly definition of opaque_mystruct.
It's convenient to automate these steps with a decent build system, for examplecmake, gnu autotools or any other with support of configure stage. Actually all mentioned systems have built-in facilities which simplify the whole task to invocation of few predefined macros.
I've been researching and thinking and took one of my potential answers and took it to the next level; I think it addresses all of my concerns. Please critique.
/** in mydata.h */
typedef const struct { const char data[12]; } mystruct;
mystruct createMystruct();
int16_t exampleMystructGetter( mystruct *p );
// other func decls operating on mystruct ...
/** in mydata.c */
typedef union {
mystruct public_block;
struct mystruct_data_s {
int64_t d1;
int16_t d2
int16_t d3;
} data;
} mystruct_data;
// Optionally use '==' instead of '<=' to force minimal space usage
_Static_assert (sizeof(struct mystruct_data_s) <= sizeof(mystruct), "mystruct not big enough");
mystruct createMystruct(){
static mystruct_data mystruct_blank = { .data = { .d1 = 1, .d2 = 2, .d3 = 3 } };
return mystruct_blank.public_block;
}
int16_t exampleMystructGetter(mystruct *p) {
mystruct_data *a = (mystruct_data*)p;
return a->data.d2;
}
Under gcc 4.7.3 this compiles without warnings. A simple test program to create and access via the getter also compiles and works as expected.

How to use zero length array in C

We can initialize a struct with zero length array as specified in the link:
Zero-Length.
I'm using the following structures:
typedef unsigned char UINT8;
typedef unsigned short UINT16;
typedef struct _CommandHeader
{
UINT16 len;
UINT8 payload[0];
} CommandHeader;
typedef struct _CmdXHeader
{
UINT8 len;
UINT8 payload[0];
} CmdXhHeader;
Now the CommandHeader.payload should point / contain to CmdXHeader struct. i.e. memory should look like:
-------------------------------------------------------------
| CommandHeader.len | CmdXHeader.len | CmdXHeader.payload ....|
-------------------------------------------------------------
I can easily malloc CmdXHeader / CommandHeader to customized length. But how to assign value to CmdXHeader payload or how to link a CmdXHeader object to the CommandHeader.payload?
My Solution
Thanks for all the reply. I solved it in the following way:
//Get the buffer for CmdXHeader:
size_t cmdXHeader_len = sizeof(CmdXHeader) + custom_len;
CmdXHeader* cmdXHeader = (CmdXHeader*) malloc(cmdXHeader_len);
//Get a temporary pointer and assign the data to it
UINT8* p;
p[0] = 1;
p[2] = 2;
.......
//Now copy the memory of p to cmdXHeader
memcopy(cmdHeader->payload, p, custom_len);
// allocate the buffer for CommandHeader
CommandHeader* commandHeader = (CommandHeader*) malloc (sizeof (CommandHeader) + cmdXHeader_len);
// populate the fields in commandHeader
commandHeader->len = custom_len;
memcpy(commandHeader->payload, cmdXHeader, cmdXHeader_len);
Now the commandHeader object have the desired memory and we can typecast with whatever way we want...
A zero-length array at the end of a struct, or anywhere else, is actually illegal (more precisely a constraint violation) in standard C. It's a gcc-specific extension.
It's one of several forms of the "struct hack". A slightly more portable way to do it is to define an array of length 1 rather than 0.
Dennis Ritchie, creator of the C language, has called it "unwarranted chumminess with the C implementation".
The 1999 revision of the ISO C Standard introduced a feature called the "flexible array member", a more robust way to do this. Most modern C compilers support this feature (I suspect Microsoft's compiler doesn't, though).
This is discussed at length in question 2.6 of the comp.lang.c FAQ.
As for how you access it, whichever form you use, you can treat it like you'd treat any array. The name of the member decays to a pointer in most contexts, allowing you to index into it. As long as you've allocated enough memory, you can do things like:
CommandHeader *ch;
ch = malloc(computed_size);
if (ch == NULL) { /* allocation failed, bail out */ }
ch.len = 42;
ch.payload[0] = 10;
ch.payload[1] = 20;
/* ... */
Obviously this is only a rough outline.
Note that sizeof, when applied to the type CommandHeader or an object of that type, will give you a result that does not include the flexible array member.
Note also that identifiers starting with underscores are reserved to the implementation. You should never define such identifiers in your own code. There's no need to use distinct identifiers for the typedef name and the struct tag:
typedef struct CommandHeader
{
UINT16 len;
UINT8 payload[0];
} CommandHeader;
I'd also suggest using the standard types uint16_t and uint8_t, defined in <stdint.h> (assuming your compiler supports it; it's also new in C99).
(Actually the rules for identifiers starting with underscores are slightly more complex. Quoting N1570, the latest draft of the standard, section 7.1.3:
All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.
All identifiers that begin with an underscore are always reserved for use as identifiers
with file scope in both the ordinary and tag name spaces.
And there are several more classes of reserved identifiers.
But rather than working out which identifiers are safe to use at file scope and which are safe to use in other scopes, it's much easier just to avoid defining any identifiers that start with an underscore.)
I assume you've got some bytes in memory and you want to find the pointer to payload?
typedef struct _CmdXHeader
{
UINT8 len;
UINT8* payload;
} CmdXhHeader;
typedef struct _CommandHeader
{
UINT16 len;
CmdXhHeader xhead;
} CommandHeader;
You could then cast your memory to a pointer to CommandHeader
uint8_t* my_binary_data = { /* assume you've got some data */ };
CommandHeader* cmdheader = (CommandHeader*) my_binary_data;
// access the data
cmdheader->xhead.payload[0];
IMPORTANT! Unless you pack your struct, it will probably align on word boundaries and not be portable. See your compiler docs for specific syntax on how to pack the struct.
Also, I'd only do what you've shown if you are consuming bytes (i.e. read from a file, or from a wire). IF you are the creator of the data, then I would heartily recommend against what you've shown.
struct _CommandHeader *commandHeader = malloc(sizeof(struct _CommandHeader)+
sizeof(struct _CmdXHeader));
Better to use payload[] instead of payload[0] in C99.
Some of C99 compilers discourage usage of zero length array.
So, in case you get an error here :
typedef struct CommandHeader
{
UINT16 len;
UINT8 payload[0];
} CommandHeader;
you can always correct it as :
typedef struct CommandHeader
{
UINT16 len;
UINT8 payload[];
} CommandHeader;

Resources