Saturday, January 12, 2019

C Flexible Array Members

I have been working on SFC/NSH (RFC7665/RFC8300) for a while. Here is how I write the code for NSH MD-Type2.


The main difference between MD1 and MD2 is the size of the context headers. For MD1, it's a fixed size ctx headers. However, MD2 supposes to be "Variable-Length Context Headers." Inside of it, it has a "Variable-Length Metadata."

Therefore, I am using FAM in C. Flexible Array Member(FAM) is a feature of declaring an array without a dimension.

For instance,

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

struct TempMD{
 /* Just an example Not for MD2 */
   int            id; 
   int           cla;
   int   struct_size;
   char ctx_header[];
}; 

// Memory allocation the struct
struct TempMD *createTempMD(struct TempMD *t,
                            int id, int cla, char ctx[]) {
    t = malloc(sizeof(*t) + sizeof(char) * strlen(ctx)); 
    t->id = id; 
    t->cla = cla; 
    strcpy(t->ctx_header, ctx); 
    t->struct_size = sizeof(*t) + sizeof(char) * strlen(t->ctx_header);
    return t;
}


int main()  { 
    struct TempMD *t = createTempMD(t, 2, 1, "0011");
    printf("Size of struct: %d\n", t->struct_size);
    return 0;
}

No comments:

Post a Comment

The Good, the Bad, and the Ugly of Working as a Software Engineer at AWS

After 5 incredible years at AWS, I have recently decided to join Zscaler. Working at Amazon Web Services is like being on a roller coaster y...