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...
- don't cast result of
malloc
in c. if have cast, you're using c++ compiler, , should usingnew
instead ofmalloc
. sizeof
operator (not function) determines size of objects of type (assize_t
, notint
), ifdata.point[i]
char *
example,sizeof data.point[i]
same valuesizeof (char *)
. common mistake assumesizeof
determines size of object pointed @ pointer; hold true array types, not pointer types.- you're leaking memory pointed @
raw
when function returns. should using automatic storage duration rather dynamic allocation there. i.e.unsigned char raw[len];
. - 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.
- 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 declareraw
in caller function, avoid being destroyed when function provided returns.
Comments
Post a Comment