使用strcpy()时出现分段错误

使用strcpy()时出现分段错误,c,strtok,strcpy,C,Strtok,Strcpy,我们添加了打印语句来检查分段错误发生的位置。在strcpy(命令、令牌)时失败; 我们如何将该部分存储到命令中?还有一种方法可以检查令牌末尾的空字符吗?strtok()在使用时是否在末尾有空字符 int main(int argc, char **argv) { char *command, *flag, *pathname, *linkname; struct stat st = {0}; char cmd[200]; char *token; //Pointer

我们添加了打印语句来检查分段错误发生的位置。在strcpy(命令、令牌)时失败; 我们如何将该部分存储到命令中?还有一种方法可以检查令牌末尾的空字符吗?strtok()在使用时是否在末尾有空字符

    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);
  }

您永远不会将值分配给
命令,更不用说为它分配指向的空间了。

在使用strcpy()将值分配给它之前,您需要初始化*命令变量。如果尝试为空指针赋值,则会出现分段错误

strcpy()的正确用法如下:

char *str = malloc(3 * sizeof(char));
char sentence[3] = "Hi\0";
strcpy(str, sentence);
printf("%s\n", str);

我也没有为token变量设置值,但它在strtok()之后正确存储和打印。我应该将命令初始化为空字符串吗?当您将
strtok
的结果分配给它时,您将一个值分配给了
token
。在将
命令
传递给
strcpy
之前,您从未给该命令赋值,告诉它将字符串复制到它包含的地址。您不知道它是空指针。这里的问题不是分配给指针。我尝试了“command=malloc(sizeof(char)*10);”这对strcpy()很好,但是有没有办法根据用户的输入进行动态内存分配呢?我不完全确定什么方法最适合您的情况。但是command=malloc((strlen(token)+1)*sizeof(char));可能对你有用。它将根据令牌的长度为命令动态分配内存空间。