c - structure cast into unsigned char array without malloc/str methods -


i've read other questions response aren't helping me much. once again, i'm not developer wood worker trying make far complicated own brain.

i work on pic alignment 4 bytes, structures define attribute((packed)).

i've found way uses malloc , str/mem-cpy, methods aren't safe interrupt, or malloc shouldn't using @ (cf. previous question)

said structure contains 16 unsigned char, 1 s16 (2 bytes) et 3 s32 (4 bytes), 30 bytes long, 4bytes alignement making 32bytes long. (char coded on 8bits).

1) wrong until here?

int len =sizeof(data_out.point[i]);     unsigned char* raw;     raw = malloc(len);     memcpy(raw, &data_out.point[i], len);     data_res[count].pdata =  malloc(len);     (int k = 0; k<len; k++)     {         data_res[count].pdata[k] = (uint8_t)(raw[k]);     }     data_res[count].datalen=len;     count++;  } 

data_out stucture (members not relevant except following one) point structure described before.

data_res structure store uchar buffer (pdata) , contains lenght , status (locked, writing, etc avoid multi-access).

1) not working 100%, result strange.

2) since yesterday understand why bad (malloc on not shared memory, casting malloc, interruption safety, etc).

how same thing without mallocs/memcpy ?

note: need debug output, going let go, don't keep things unfinished...

  1. don't cast result of malloc in c. if have cast, you're using c++ compiler, , should using new instead of malloc.
  2. sizeof operator (not function) determines size of objects of type (as size_t, not int), if data.point[i] char * example, sizeof data.point[i] same value sizeof (char *). common mistake assume sizeof determines size of object pointed @ pointer; hold true array types, not pointer types.
  3. you're leaking memory pointed @ raw when function returns. should using automatic storage duration rather dynamic allocation there. i.e. unsigned char raw[len];.
  4. you should performing machine-independent serialisation, e.g. translating each field value doesn't depend upon machine architecture, if you're planning on transporting data other machines.
  5. finally, answer question, way can substitute data_res[count].pdata = malloc(len); seems need other object (see automatic storage duration above) point instead, i.e. data_res[count].pdata = raw;... might need declare raw in caller function, avoid being destroyed when function provided returns.

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -