C
Cadderly
Hi all,
I have the following pseudo-c-code which parse a command line, and puts the
command and its arguments in an array, and I can't figure out where/how I
should use free:
main(void):
char ** command_arr;
parser(command_arr);
parser(char ** command_arr):
command_arr = malloc ( argument_number * sizeof(char *);
while ( there is an argument arg ) {
*(command_arr + command_arr_index) = malloc ( strlen(arg) + 1 )
strcpy (*(command_arr + command_arr_index), arg)
command_arr_index++;
}
*(command_arr + command_arr_index) = NULL;
well, what i wonder is if, in the main fonction, free(command_arr)
deallocates 'malloced' spaces in the parser (with strlen), or should I write
something like that?
while ( *(command_arr + command_arr_index) != NULL ) {
free( *(command_arr + command_arr_index) );
command_arr_index++;
}
free(command_arr);
I know the code is not rigorous but the question is mainly on the usage of
malloc/free..
Thanks
I have the following pseudo-c-code which parse a command line, and puts the
command and its arguments in an array, and I can't figure out where/how I
should use free:
main(void):
char ** command_arr;
parser(command_arr);
parser(char ** command_arr):
command_arr = malloc ( argument_number * sizeof(char *);
while ( there is an argument arg ) {
*(command_arr + command_arr_index) = malloc ( strlen(arg) + 1 )
strcpy (*(command_arr + command_arr_index), arg)
command_arr_index++;
}
*(command_arr + command_arr_index) = NULL;
well, what i wonder is if, in the main fonction, free(command_arr)
deallocates 'malloced' spaces in the parser (with strlen), or should I write
something like that?
while ( *(command_arr + command_arr_index) != NULL ) {
free( *(command_arr + command_arr_index) );
command_arr_index++;
}
free(command_arr);
I know the code is not rigorous but the question is mainly on the usage of
malloc/free..
Thanks