无法找到分段故障的原因

时间:2016-07-31 12:44:09

标签: c++ segmentation-fault

我正在编写以下代码来根据它们的长度来处理字符串,但是我得到了分段错误,用Google搜索它并发现它与指针相关但却无法找出相同的原因。

#include <string.h>
#include <iostream.h>
#include <stdio.h>

int main()
{
   char input[500];
   strcpy(input, "quick brown fox jumps on lazy dog");
   const char s[2] = " ";
   unsigned int num = 7;
   unsigned int lent;
   cin >> num;
   char *token;
   token = strtok(input, s);
   while( token != NULL ) 
   {
        lent= strlen(token);
        if(lent <= num)
            printf( " %s", token );
        token = strtok(NULL, s);
        if(strlen(token) <= (num-lent))
            printf("%s",token );
        printf("\n");
   }

   return(0);
}

1 个答案:

答案 0 :(得分:4)

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><img src="img/logo.png" height=30 width=41></a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> Home</a></li> <li><a href="aboutus.html"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span> About</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> Menu <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Appetizers</a></li> <li><a href="#">Main Courses</a></li> <li><a href="#">Desserts</a></li> <li><a href="#">Drinks</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Specials</li> <li><a href="#">Lunch Buffet</a></li> <li><a href="#">Weekend Brunch</a></li> </ul> </li> <li><a href="contactus.html"><i class="fa fa-envelope-o"></i> Contact</a></li> </ul> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="email" class="form-control" placeholder="Email"> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Password"> </div> <label class="checkbox-inline"> <input type="checkbox" name="approve" value=""> <p id="rememberme">Remember me</p> </label> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </div> </nav>

您到达输入字符串的末尾。此行token = strtok(NULL, s);变为token。但是,您会立即使用NULL

在任何可能取消引用它的操作之前检查strlen(token)