简体   繁体   中英

Segmentation fault when dividing string using malloc

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. eg 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.

 while(split != NULL){

Instead of check split for NULL you need to check if ptr is NULL .

If it is NULL then your malloc will allocate 1 byte and memory's dereference will cause problems due to overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM