首页 文章

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

提问于
浏览
-1

我们添加了print语句来检查分段错误发生的位置 . 它在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);
  }

2 回答

  • 0

    您永远不会为 command 分配值,更不用说为它指定空间 .

  • 0

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

    正确使用strcpy()将是这样的:

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

相关问题