Helo, I've got a homework assignment to write a simple shell in C, using fork(), malloc() and execv() and I have the following problem: I need to free the memory for a variable, which I'm returning in a function
char** parse_cmdline(const char* line){
int size = strlen(line);
char** array_of_strings = malloc((sizeof(char*)*(size)))
char* pch = strtok(line," \n\t\r");
int co = 0;
int co2;
while (pch != NULL)
{
array_of_strings[co]=(char*)malloc((sizeof(char)*strlen(pch))+1);
strcpy(array_of_strings[co], pch);
pch = strtok (NULL, " \n\t\r");
++co;
}
array_of_strings[co] = NULL;
return array_of_strings; //that's the variable I need to free
}
And here is the whole program
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
char** parse_cmdline(const char* line){
int size = strlen(line);
char** array_of_strings = malloc((sizeof(char*)*(size)));
char* pch = strtok(line," \n\t\r");
int co = 0;
int co2;
while (pch != NULL)
{
array_of_strings[co]=(char*)malloc((sizeof(char)*strlen(pch))+1);
strcpy(array_of_strings[co], pch);
pch = strtok (NULL, " \n\t\r");
++co;
}
array_of_strings[co] = NULL;
return array_of_strings;
}
int main(int argc, char *argv[]){
char line[512];
printf("Welcome to My shell!\n");
while(1){
printf(">$");
gets(line);
pid_t pid = fork();
if (pid == -1){
perror("");
}else if(pid == 0){
execvp(parse_cmdline(line)[0], parse_cmdline(line));
}else{
wait(pid);
}
}
return 0;
}
Please, help me