I am using ncurses to create my own terminal. I get the string and save it in a 2D array, buffer[80][256]. I get the string using getstr(buffer[i]). Then I have the following in the main function;
while (strcmp(buffer[i],"exit")!=0) {
strcpy(command,buffer[i]);
printw("%s\n",command);
//calls the function commands found in another source file
commands(buffer[i]);
mvwin(childwin, y, x);
wnoutrefresh(childwin);
i++;
printw("%s",prompt);
getstr(buffer[i]);
doupdate();
}
//source file where one finds commands;
//global array
char*final[40];
void commands (char input[]){
char **buffer =split(input);
...
}
//creating segmentation fault
char **split(char input[]){
char *ptr;
int i=0;
ptr = strtok(input," ");
while(split != NULL){
final[i] = malloc(strlen(ptr)+1);
strcpy(final[i],ptr);
ptr = strtok(NULL," ");
i++;
}
return final;
}
What the above function is doing; it is receiving the input by the user buffer[i] and it is dividing the strings into separate elements within array buffer in function commands. e.g. if the user enters print hello my name is, buffer in function commands with hold; buffer[0] = print, buffer[1] = hello buffer[2] = my ....
From my testing it seems like the malloc is the thing causing it, but I have no idea on how to solve it.
Thank you very much in advance.