-1

I have created an array of structs. Each element of the array is meant to allocate up to 4 digits; there can be less digits. Initially, the are set to 0. I have some memory leaks in program and I would like to ask about the first one:

#include <stdlib.h>

#define ELEMENTS 8
#define NUM_INT 4   //Number of digits

typedef struct sth {
    int* numbers;
    int how_many;  //How many cells with 4 digits
} sth;


void create(sth** tab) {
    *tab = realloc(*tab, ELEMENTS * sizeof(**tab)); 
    for (int i = 0; i < ELEMENTS; i++) {
        sth cell; 
        cell.numbers = calloc(NUM_INT, sizeof (*cell.numbers));
        cell.how_many = 1;
        (*tab)[i] = cell; // Put in original array.
     }
     (*tab)[ELEMENTS-2].numbers[0] = -1; // Don't bother about the values
     (*tab)[ELEMENTS-1].numbers[0] = 1;
}

void clear(sth** arr) {
    free(*arr);
    *arr = NULL;
}

int main(void) {
    sth* arr = NULL; // Don't need to initialise to null here.
    create(&arr);
    //There have been functions, but I commented them out
    clear(&arr);
    return 0;
}

When I run the program, I get by Valgrind:

    ==58759== 448 bytes in 28 blocks are definitely lost in loss record 1 of 1                                       
    ==58759==    at 0x4837B65: calloc (vg_replace_malloc.c:752)                                                             
    ==58759==    by 0x1091D6: create (address_of_a_file)                       
    ==58759==    by 0x10A3F4: main (address_of_a_file)                                 
    ==58759== 

Earlier I have used realloc instead of calloc and vilgrind indicated line:

sth cell;
sth cell.numbers = NULL;
cell.numbers = realloc(cell.numbers, NUM_INTS*sizeof(*cell.numbers));  //this line

As I have written, in the whole program occur memory leaks, but I want to track the first source of them.

For me it seems as if I have created new allocated memory and have not freed the previous content. However I don't know, what is the cause of the problem here, because I free the memory at the end of the program.

I would appreciate your suggestions and explanations.

Funny
  • 193
  • 8

1 Answers1

2

The solution suggested by @AntiiHappala was:

void clear(sth** arr) {
    for (int i = 0; i < ELEMENTS; i++) {
          free((*arr)[i].numbers);
    }
    free(*arr);
}
Funny
  • 193
  • 8