4
What is the right way to use the free()
in that 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));
4
What is the right way to use the free()
in that 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));
7
Assuming the allocation is the way you really need it, there’s no need to complicate it, just use a free()
simple:
free(ls_options);
free(ls_buffer_send);
Take advantage of and simplify allocation:
char **ls_options = malloc(200);
char *ls_buffer_send = malloc(350);
I put in the Github for future reference.
Avoids even some problems.
1
Traverse the entire array by releasing memory for each active element.
How is declaring a fixed size for the variable should be done more or less 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 as NULL
at the initialization of ls_options
Browser other questions tagged c pointer memory allocation
You are not signed in. Login or sign up in order to post.
I have the impression that using the free in this way (direct in the pointer vector) all references will be lost. This would not end up generating memory Leak?
– Pilati
What references?
– Maniero
ls_options
is not an array of 200 "references" tochar *
? That is, 200 pointers to string?– Pilati
I didn’t see it in this code. I saw 200 characters. I made the caveat that the answer is based on what he posted. If the code does other things than this then it may have to do other things. Note that it is allocating characters, not pointers.
– Maniero
Good,
char *
is a character vector, a string.char **
is an array for strings. If you delete the string array all strings will still be allocated right?– Pilati
The code is allocating 200 bytes, that’s all, if he’s going to use it in creative ways I don’t know, but it’s the only thing he’s doing. And the pointer where this allocation occurred will be played on
ls_options
. The code does nothing else.– Maniero
Let’s go continue this discussion in chat.
– Pilati