strtok()空字符串输入的分段错误

时间:2016-09-09 17:10:03

标签: c segmentation-fault strtok

    <RatingBar
        android:id="@+id/MyRating"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:isIndicator="true"
        android:numStars="5"
        android:stepSize="0.1"
        android:layout_above="@+id/textQuestion2"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp"
        android:layout_alignParentRight="true" />

在上面的代码片段中,我试图将whitspace上的字符串标记为分隔符。每当我以public class SurveyActivity extends AppCompatActivity implements getQuestionsAsyncTask.GetQuestions,RatingBar.OnRatingBarChangeListener{ private ArrayList<Question> mQuestionsArrayList; private TextView mTextQuestion1,mTextQuestion2; private RatingBar ratingbar1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_survey); Button next = (Button)findViewById(R.id.btn_next); final RatingBar ratingBar = (RatingBar)findViewById(R.id.MyRating); ratingBar.setOnRatingBarChangeListener(this); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { float rating=ratingBar.getRating(); Toast.makeText(getApplicationContext(),"Your Selected Ratings : " + String.valueOf(rating),Toast.LENGTH_LONG).show(); } }); } @Override public void onRatingChanged(RatingBar ratingBar, float v, boolean b) { v = ratingBar.getRating(); Toast.makeText(getApplicationContext(), "Your Selected Ratings : " + String.valueOf(v), Toast.LENGTH_LONG).show(); } #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_INPUT_LENGTH 1024 char *readline(FILE* fp, int max_length) { //The size is extended by the input with the value of the provisional char *str; int ch; int len = 0; int current_max = max_length; str = (char*)malloc(sizeof(char)*current_max); if(!str) return str; while((ch = fgetc(fp))!=EOF) { /* Separate newline handling from EOF handling */ if((char)ch == '\n') { str[len] = '\0'; return str; } str[len++] = ch; if(len == current_max) { current_max = current_max + max_length; str = realloc(str, sizeof(char)*current_max); if(!str) return str; } } str[len] = '\0'; return str; } int main(void) { char *input, *token; input = readline(stdin, MAX_INPUT_LENGTH); printf("BEFORE\n"); token = strtok(input, " "); //Segmentation Fault Here printf("AFTER"); //control never reaches here on " " or "\n" input. } 提供输入时,newline(press ENTER)会调用段错误。根据我的理解,它应该返回a sequence of whitespaces我应该在稍后的理智检查中处理,但这并没有真正发生。

请帮助我,我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您对故障发生位置的分析不正确

printf("AFTER"); //control never reaches here on " " or "\n" input.

实际上,控制确实到达那里。你只是没有看到&#34; AFTER&#34;消息,因为那里没有换行或冲洗。将代码更改为此,神秘感将会消失:

printf("AFTER\n");

我打赌你不能用你的MCVE复制错误,因为它确实到达main的末尾,这会刷新输出。你忘记了&#34; V&#34;在MCVE。您需要验证它是否会复制问题。