How should you correctly terminate these variables without having a chance of memory leak?

3

What is the correct way to use free() in this case, where ls_options will contain several ls_buffer_send ?

char **ls_options = (char**) malloc (200*sizeof(char));
char *ls_buffer_send = (char*) malloc (350*sizeof(char));
    
asked by anonymous 27.07.2016 / 20:10

2 answers

6

Assuming that the allocation is the way you really need it, you do not have to complicate it, just use a simple free() :

free(ls_options);
free(ls_buffer_send);

Leverages and simplifies allocation:

char **ls_options = malloc(200);
char *ls_buffer_send = malloc(350);
    
27.07.2016 / 21:22
1

Scroll through the vector by releasing the memory for each active element.

As you are declaring a fixed size for the varable should be done something like this:

int i;
for(i=0; i<200; i++){
    if(ls_options[i] != NULL){
        free(ls_options[i]);
    }
}
free(ls_options);

But for this to work properly all elements must be set to NULL at startup of ls_options

    
27.07.2016 / 20:25