Search code examples
pascallazarusfreepascal

Pascal Segmentation Fault parsing Text File


I am working on a Question/Answer UI application in Pascal / Lazarus. My problem is that upon invoking below code through a button click, the program crashes with a Segmentation Fault error.

// more declarations... (UI Form, Buttons, ...)

type
  TQuestion = class(TObject)
    title: string;
    answers: array of string;
    correct: integer;
  end;

var
  questions: array of TQuestion;

procedure TForm1.BStartClick(Sender: TObject);
var
  i: integer;
  j: integer;
  line: string;
  arrayLength: integer;
  question: TQuestion;
  stringList: TStringList;
begin
  stringList := TStringList.create;
  stringList.LoadFromFile('questions.txt');

  for i := 0 to stringList.Count - 1 do ;
  begin
    line := stringList[i];
    if (length(line) >= 2) then
      if (line[2] = ' ') and ((line[1] = '-') or (line[1] = '+')) then
      begin
        arrayLength := length(question.answers);
        SetLength(question.answers, arrayLength + 1);
        question.answers[arrayLength] :=
          Copy(line, 2, Length(line) - 1);

        if zeile[1] = '+' then
          question.correct := arrayLength;
      end
      else
      begin
        question := TQuestion.Create;
        question.title := line;

        arrayLength := length(questions);
        setLength(questions, arrayLength + 1);
        questions[arrayLength] := question;
      end;
  end;
  BStart.Visible := False;
end;

Solution

  • Well, my Pascal knowledge goes to 10 to 15 years ago. However, I can see that you have an extra semicolon at the end of this line:

    for i := 0 to stringList.Count - 1 do ;