malloc - memory leak heap and stack compilation issue C -


i've got qestion, i'm using sourgery c++ toolchain, , compiler leave me write sentence:

for(i=0;i<size_of_categories;i++){      size_t size_of_tmp = sizeof(char) * (hostlink_config_string_max_len * (categories[i].key_len));      char tmp[size_of_tmp];     memset(tmp,0,(size_of_tmp));         get_hostlink_count[i]++;      if(categories[i].time == get_hostlink_count[i]){          if(format == csv){              csv_this_category_values(categories,i,tmp,size_of_tmp);             strncat(buffer,tmp,buff_len);          }else if (format == json){              xi_json_this_category_values(categories,i,tmp,size_of_tmp);             js_this_cat = json_loads(tmp,json_decode_any,null);             json_array_extend(js_arr,js_this_cat);              json_array_clear(js_this_cat);             json_decref(js_this_cat);         }          get_hostlink_count[i] = 0;      }     //free(tmp); } 

my issue sentece alloc memory in stack or in heap? cause memory leak because made in loop? equivalent make malloc , @ end of loop free?

size_t size_of_tmp = sizeof(char) * (hostlink_config_string_max_len * (categories[i].key_len));      char tmp[size_of_tmp]; 

since not doing mallocs, there won't memory leak in particular piece of code. however, can't declare tmp array non-constant size. is, can't char tmp[size_of_tmp] size_of_tmp not being constant (which isn't because depends on categories[i].key_len).

what can use malloc or calloc allocate memory array on heap this

char *tmp = (char*)malloc(size_of_tmp); 

or this

char *tmp = (char*)calloc(size_of_tmp, sizeof(char)); 

calloc initializes of allocated memory zero, don't have use memset.

if want avoid memory leaks have free allocated tmp array @ end of each loop iteration.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -