Home > Net >  I didn't free my malloced pointers, so why am I not leaking memory?
I didn't free my malloced pointers, so why am I not leaking memory?

Time:09-11

I malloced two dimensional arrays and one dimensional array. it's like

    int *each_len = (int *)malloc(sizeof(int) * (total_line));
    char **arr = malloc(sizeof(char *) * (total_line   1));
    t_dict *dict = malloc(sizeof(t_dict) * (total_line   1));

After I used them I checked if memory is leaking before the main function ends. it is like

int main(void)
{

    int     total_line;
    int     *each_len;
    char    **arr;
    t_dict  *dict;

    total_line = get_linenum();
    each_len = (int *)malloc(sizeof(int) * (total_line));
    arr = malloc(sizeof(char *) * (total_line   1));
    dict = malloc(sizeof(t_dict) * (total_line   1));
    len_store(each_len);
    store_line(arr, each_len);
    set_dict(dict, arr, total_line);
    divider(342, dict);
    // free(each_len);
    // free_arr(arr, total_line);
    // free_dict(dict, total_line);
    system("leaks a.out > leaks_result_temp; cat leaks_result_temp | grep leaked && rm -rf leaks_result_temp");

    return (0);
}

The problem is even if I didn't free my allocated space, the message tells me there is no leak.

Process 46827: 0 leaks for 0 total leaked bytes.

why is this happening? I didn't free them so they should be leaked right?? is this spaces automatically freed?

if i use just "system("leaks a.out") it shows

leaks Report Version: 4.0

Process 47508: 240 nodes malloced for 11 KB

Process 47508: 0 leaks for 0 total leaked bytes.

CodePudding user response:

leaks does not just look for memory that has been allocated and not freed. It looks for memory that has been allocated and not freed and for which leaks cannot find a pointer to that memory in the memory of the process.

So, if some variable in the program, or some other memory that leaks inspects, has the address of a piece of allocated memory, that memory is not considered leaked because the program still has control of it—it could use the pointer to access the memory or to free it.

(This means that leaks can have some false positives. In some situations, a program might keep a pointer into the middle of allocated memory and later free the memory by reconstructing the start address. For example, certain signal filter algorithms might be written to use non-negative indices for incoming data and negative indices for outgoing data. So the program might allocated memory, change the pointer to point to where it was the “zero” index to be, use the memory with that new base address, and later subtract from the updated pointer to get the address to pass to free. If leaks is called when the program memory only contains the adjusted base address, it would not see the address of the allocated memory and might report it as leaked.)

  •  Tags:  
  • c
  • Related