C - Trying to build a simple shell in linux and having trouble with strtok, realloc in a loop -


trying build shell implementation in linux assignment , having trouble. following error after running 3/4 times loop

* error in `./1': realloc(): invalid next size: 0x000000000132c150 * aborted (core dumped)

i have left parts of code out it's long , know there's no issues them. if there's other parts need can add them too. in advance :)

note: argc , argv global variables

int argc = 0; char **argv = null;   int main(void) {        while(1)     {         catch_signal();         printdate();         readcommand();          if(strcmp(argv[0], "cd") == 0)         {             changedirectory();         }         else         {             executecommand();         }         //free(argv);     }    }  void readcommand() {     char *buffer = null;     char *token = " ";     char *p;      size_t len = 0;     int = 0;      getline(&buffer, &len, stdin);     p = strtok(buffer, "\n");     p = strtok(buffer, token);      while(p)     {         argv = realloc(argv, sizeof(char *) * ++i);          argv[i - 1] = p;         p = strtok(null, token);     }     argc = i;     argv[argc] = null;     free(p); }  void executecommand() {     int status;     pid_t pid;      if((pid = fork()) < 0)     {         printf("error: forking child process failed.");     }     else if(pid == 0)     {        if(execvp(argv[0], argv) < 0)        {            printf("error");            exit(1);        }     }     else     {        while(wait(&status) != pid);     } } 

you reallocating argv array 1 pointer short. there not enough space final null pointer. consider replacing while(p) loop code:

if (!p) {     /* deal empty command line */ }  while (p) {     argv = realloc(argv, sizeof(char *) * (i + 2));     argv[i++] = p;     p = strtok(null, token); } 

p should start null if user entered actual command. if buffer contains empty string or blank one? strtok return null directly in these cases. should ignore such command lines.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -