2016-04-16 35 views
-2

我一直在试图弄清楚我的这段代码有什么问题。所以到处都是我的代码,我想我已经找到了罪魁祸首。这是这块代码在这里造成它我该如何解决这种分段故障?

if (strcmp(input, "load 1") != 0 || strcmp(input, "load 2") != 0 || strcmp(input, "quit") != 0) 
    { 
     Player player; 
     Position position; 
     Direction direction; 

     char* tok; 
     char* firstInput=0; 
     char* secondInput=0; 
     char* thirdInput=0; 
     char* fourthInput=0; 
     int x; 
     int y; 
     char str[10]; 
     char str2[10]; 


     tok = strtok(input, " "); 
     strcpy(firstInput, tok);    
     tok = strtok(NULL, ", "); 
     strcpy(secondInput, tok);   
     tok = strtok(NULL, ", "); 
     strcpy(thirdInput, tok);   
     tok = strtok(NULL, ""); 
     strcpy(fourthInput, tok);    

     strcpy(str, secondInput); 
     x = atoi(str); 
     strcpy(str2, thirdInput); 
     y = atoi(str2); 

     if(strcmp(firstInput, "init") == 0) 
     { 
      if(x >= 0 && x <= 9) 
      { 
       if(y >= 0 && y <= 9) 
       { 
        if (strcmp(fourthInput,"north") == 0 || (strcmp(fourthInput,"south")) || (strcmp(fourthInput,"west") == 0) || (strcmp(fourthInput,"east") == 0)) 
        { 
         position.x = x; 
         position.y = y; 

         if(strcmp(fourthInput,"north") == 0) 
         { 
          direction = NORTH; 
         } 
         if(strcmp(fourthInput,"south") == 0) 
         { 
          direction = SOUTH; 
         } 
         if(strcmp(fourthInput,"west") == 0) 
         { 
          direction = WEST; 
         } 
         if(strcmp(fourthInput,"east") == 0) 
         { 
          direction = EAST; 
         } 
         initialisePlayer(&player, &position, direction); 
         placePlayer(board, position); 
         displayDirection(direction); 
        } 
       } 
      } 
     }      
    } 

从我所知道的分段故障意味着一个内存问题。我已确保有足够的空间容纳一切。实际上发生了什么?

+1

可能的重复[如何调试段错误?](http://stackoverflow.com/questions/29324796/how-to-debug-segmentation-fault) – OrangeDog

+2

嗯,你还没有分配任何内存。 'firstInput'仍然是0. –

+1

哪条线段错误?什么是回溯? – fluter

回答

1

正如在评论中提到的,firstInput和它的兄弟姐妹没有任何内存分配到你可以strcpy到。它们是NULL,这导致了分段错误。

你可以分配内存或使这些变量成为本地数组,但你并不需要这些。 strtok将指针返回到input。只要input未被覆盖,这些都是有效的。在将下一行读入input之前,您只能使用这些指针来分析当前行,所以没关系。

摆脱中介tok,并直接存储令牌的结果:

char* firstInput = NULL; 
    char* secondInput = NULL; 

    firstInput = strtok(input, " "); 
    if (firstInput) secondInput = strtok(NULL, ", "); 

    // analyse input 

当指针处理,确保访问之前测试的NULL。不能保证用户输入包含正好四个令牌(或任何令牌)。

0

你可以从这里开始:

char* firstInput=0; 
... 
strcpy(firstInput, tok); 

其中firstInput仍然是NULL,并且没有内存分配给它,但你想tok复制到其中。

使用malloc()分配内存,这样的:

firstInput = malloc(sizeof(char) * (strlen(tok) + 1)); 
if (firstInput==NULL) 
    exit (1); 

这应该让你开始你的调试。 :)