Hello there,
this might be a silly question but I am a bit confised about the case and I wanted to ask around. I need to allocate memory for an object that looks like this:
Code:
typedef struct{
uint32_t len;
uint8_t* data;
} cdcRaw_t;
It contains pointer to data, with should be also alocated with length of value len.
So my aproach looks like this (test program)
Code:
#include <stdio.h>#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
uint32_t len;
uint8_t* data;
} cdcRaw_t;
int main(void)
{
uint8_t data[] = "abcdefghijklmn";
uint32_t len = 14;
// first allocate memory for the struct
cdcRaw_t* item = malloc(sizeof(cdcRaw_t));
item->len = len;
// then allocate memory for data within struct
item->data = malloc(sizeof(item->len));
// copy the data
memcpy(item->data, data, item->len);
int i;
for (i = 0; i < item->len; i++)
{
printf("item %c at index %i \n", item->data[i], i);
}
// double free
free(item->data);
free(item);
return 0;
}
:
In this aproach I have to malloc twice and free twice... Is there a more efficient way to allocate and free memory for this struct? Important note- for each struct object, the length of data varies.