-1

What is the correct way to allocate memory for temp_comercial temp_active_substance ? could this allocation cause a memory leak? I need just an answer to a correct form of allocate memory for the char pointers ..

int * temp_quantity;
void ** temp_pointers;
char ** temp_comercial_name;
char ** temp_active_substance;
char ** temp_manufacturer;
char ** temp_expiry_date;
int insertion_index, split, new_key, i, j;

new_leaf = make_leaf();

temp_keys = malloc( order * sizeof(int) );
if (temp_keys == NULL) {
    perror("Temporary keys array.");
    exit(EXIT_FAILURE);
}
temp_quantity = malloc( order * sizeof(int) );
if (temp_quantity == NULL) {
    perror("Temporary quantity array.");
    exit(EXIT_FAILURE);
}
temp_pointers = malloc( order * sizeof(void *) );
if (temp_pointers == NULL) {
    perror("Temporary pointers array.");
    exit(EXIT_FAILURE);
}

temp_comercial_name = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_comercial_name[i] = malloc( sizeof(char) * 20); 

temp_active_substance = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_active_substance[i] = malloc( sizeof(char) * 20); 

temp_manufacturer = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_manufacturer[i] = malloc( sizeof(char) * 20); 

temp_expiry_date = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_expiry_date[i] = malloc( sizeof(char) * 20); 
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
user2979239
  • 9
  • 1
  • 2

1 Answers1

4

This code alone can not decide if leak or not..

temp_comercial_name = malloc(order);
for(i = 0 ; i < order ; i++)
    temp_comercial_name[i] = malloc( sizeof(char) * 20); 

You have make sure you delete / free memory in loop as below..

for (i=0; i<order; i++) {
   free(temp_comercial_name[i] );
}
free(temp_comercial_name);

Edit: Setting NULL after free. There are quite a few discussion on this topic on SO.

NULL after free or not

Community
  • 1
  • 1
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31
  • `sizeof(char)` is redundant, as the standard _guarantees_ a char is bound to be `1` in size. best still to allocate memory as `var_name = malloc(n*sizeof(*var_name));`, though... if you decide to change the type of a given var, you don't have to then spend eons changing all allocation-related code, too – Elias Van Ootegem Jan 21 '14 at 08:40