-1

We added print statements to check where the segmentation fault was happening. It fails at strcpy(command, token); How can we store that part into command? Also is there a way to check for the null character at the end of token? Does strtok() have a null character at the end when used?

    int main(int argc, char **argv)
{
  char *command, *flag, *pathname, *linkname;
  struct stat st = {0};
  char cmd[200];
  char *token; //Pointer
  int counter = 1; //Counter variable
  FILE *fp;
  char mode2[] = "0750"; //To set the permission of a file/path
  long j;
  char mode[] = "0640"; //To set the permission of a file/path
  long i;

  fgets(cmd, 200, stdin);
  printf("print for cmd: %s\n", cmd);

  //User input is tokenized to determine the proper commands are entered and executed
  token = strtok(cmd, " "); //Input is tokenized by white spaces.
  printf("token: %s\n", token);

  strcpy(command, token);

    printf("print for command: %s\n", command);

  if(token == NULL)
  {
        printf("Error with command input.\n");
        exit(EXIT_FAILURE);
  }
Brad Bieselin
  • 107
  • 1
  • 11

2 Answers2

0

You never assign a value to command, much less allocate space for it to point to.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • I didn't set a value for the token variable either, but it stores and prints properly after the strtok(). Should I initialize command to empty string? – Brad Bieselin Dec 09 '18 at 03:22
  • You assigned a value to `token` when you assigned the result of `strtok` to it. You never assigned a value to `command` before passing it to `strcpy` telling it to copy a string to what address it contains. – Scott Hunter Dec 09 '18 at 03:24
0

You need to initialize you *command variable before assigning a value to it with strcpy(). The segmentation fault will happen if you try to assign a value to a NULL pointer.

A correct use of strcpy() would be like this:

char *str = malloc(3 * sizeof(char));
char sentence[3] = "Hi\0";
strcpy(str, sentence);
printf("%s\n", str);
Mars Gao
  • 69
  • 6
  • You don't know it is a NULL pointer. And the problem here isn't assigning to a pointer. – Scott Hunter Dec 09 '18 at 03:26
  • I tried 'command = malloc(sizeof(char) * 10);' and that works fine for strcpy() but is there any way to do dynamic memory allocation depending on the input from the user? – Brad Bieselin Dec 09 '18 at 03:31
  • I am not totally sure what can be the best method for your situation. But command = malloc((strlen(token) + 1) * sizeof(char)); might work in your case. It will dynamically allocate memory space for command based on the length of token. – Mars Gao Dec 09 '18 at 03:34