0

I get 4 still reachable blocks and I have no idea why. It seems I free everything I have allocated. But, it still shows me 4 reachable blocks when I run valgrind.

I am trying to discover if I have freed allocated stuff in the right way.

Here is my code:

struct builtin *table[CMDNUM];

void freeBuiltinsTable(){
    int i = 0;
    for(i = 0; i < CMDNUM; i++){
        free(table[i]);
    }
}

void initializeBuiltins(){
    
    table[0] = calloc(1, sizeof(struct builtin));
    table[0]->name = "exit";
    table[0]->f = my_exit;
    
    table[1] = calloc(1, sizeof(struct builtin));
    table[1]->name = "cd";
    table[1]->f = my_cd;
    
}

And here I am freeing linked list:

struct cmd{
    char *command[2+MAXARGS]; 
    struct cmd *next;
};

void freeLL(){
    struct cmd *ptr = cmdListFront;
    struct cmd *temp;
    while(ptr != NULL){
        temp = ptr;
        ptr = ptr->next;
        free(temp);
    }
}

And the last one I am allocating and freeing a line that is allocated for user input:

char *line = calloc(MAXLINE+1, 1);
 while (fgets(line, MAXLINE+1, stdin)) {
        ...
        free(line);
        line = calloc(MAXLINE+1, 1);
 }
    
free(line);

Any mistakes in my frees?

halfer
  • 19,824
  • 17
  • 99
  • 186
RUstar
  • 37
  • 5
  • In your second case, it's inefficient to `free` and then `calloc` again. If you need the memory to be zero'd out, just do that yourself (but since you're using `fgets` you probably don't even need that). – mah Mar 20 '15 at 17:16
  • Why are you free'ing and allocating `line` within your loop? – jschultz410 Mar 20 '15 at 17:16
  • char *command[2+MAXARGS]; is an array of _pointers_ to characters, If you want the space allocated, then write char command[2+MAXARGS]; – Paul Ogilvie Mar 20 '15 at 17:17
  • If the blocks are reachable and not lost, then you must have some pointers (e.g. - in globals) laying around still pointing to allocated memory. Some library calls allocate memory and never free it, which can similarly be reported as reachable blocks. In which function does valgrind say the blocks were allocated? Run it again with `--show-reachable=yes --leak-check=full --num-callers=20`. – jschultz410 Mar 20 '15 at 17:21
  • Have you looked at http://stackoverflow.com/questions/3840582/still-reachable-leak-detected-by-valgrind - yo umight not actually have a problem – kdopen Mar 20 '15 at 17:38
  • @jschultz410 shouldn't I free line within a loop? If it is being reused.. I guess I should free it and allocate again for later use in fgets? – RUstar Mar 20 '15 at 17:42
  • @RUstar No good reason to do so that I can see. Just reuse the existing buffer. – jschultz410 Mar 20 '15 at 18:10

0 Answers0