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

时间:2018-12-09 03:17:31

标签: c strtok strcpy

我们添加了打印语句,以检查发生分段错误的位置。它在strcpy(command,token)处失败; 我们如何将该部分存储到命令中?还有一种方法可以检查令牌末尾的空字符吗?使用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);
  }

2 个答案:

答案 0 :(得分:0)

您永远不会为model.add(GlobalMaxPooling1D()) model.add(Dense(1, activation='sigmoid')) #sigmoid activation to return number from 0-1 model.compile(loss='binary_crossentropy', optimizer='adam') model.summary() model.fit(x, y, epochs=1000) 分配一个值,更不用说为其分配空间了。

答案 1 :(得分:0)

在使用strcpy()为其分配值之前,需要初始化* command变量。如果您尝试将值分配给NULL指针,则会发生分段错误。

正确使用strcpy()会像这样:

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