i have dynamically allocated vector of special struct, , trying free software crashes
the structure :
typedef struct { type_e type; union { char m_char; int m_int; // more types (non of them pointer) } my_data; } data_t; where type enum contain possible data types.
i allocate , initialize vector follows
void vector(data_t **vec, uint32_t start_element, uint32_t end_element, type_e type) { uint32_t i; data_t *vec_ptr; *vec=(data_t *)malloc((size_t) ((end_element-start_element+1) * sizeof(data_t))); vec_ptr = *vec; if (!vec_ptr) { // write error } (i =start_element; <= end_element + 1; i++) { vec_ptr->type = type; switch (type) { case uint32: vec_ptr->my_data.m_int = 0; break; // more possible cases default: break; } (vec_ptr)++; } } i call function follows
data_t *lvector = null; vector(&lvector,0,10,int32) but when try free allocated memory follows,
free (lvector+start_element-1); i tried
free (lvector+start_element); and
free (lvector); were start_element = 0 (in case)
but in cases, crash. doing wrong ?
this parameter says array of pointers type 'data_t'
data_t **vec, however, line:
*vec=(data_t *)malloc((size_t) ((end_element-start_element+1) * sizeof(data_t))); allocates memory array of 'data_t' not array of pointers 'data_t'
in c, not cast returned value malloc
the parameter malloc() automatically 'size_t' casting 'size_t' clutters code
this line:
for (i =start_element; <= end_element + 1; i++) iterates on array index 0 index 11 however, valid index 0 10 c array indexs start 0 , end @ sizeof(array) -1
this line:
(*vec)->type = type; is expecting 'vec' array of pointers struct. but, mentioned earlier, not
this line:
*vec = *vec + sizeof(data_t); is stepping through array of struct however, looses pointer malloc'd memory, resulting in memory leak because pointer malloc'd memory lost cannot passed free()
this line:
*vec = *vec - ((end_element-start_element+1) * sizeof(data_t)); doesn't quite work, because prior 'for' statement iterates 1 many times.
strongly suggest indexing off 'vec' rather changing vec contents. i.e. vec[i]
Comments
Post a Comment