为什么我会出现段错误?

时间:2020-06-10 01:25:18

标签: c++ segmentation-fault

我是C ++的初学者,并且正在通过将学生的答案与答卷(“ 112341423114322314231231442314231223422”)进行比较,为学生的答案(“ 11 3 1133 22322314231432211231 34 2”)评分的课程。我必须比较学生答案的每个值,如果它们匹配,则加2分。如果不是,请减去1。现在,如果答案为空,那么我对学生的成绩没有任何帮助。

现在,代码如下:

//
#ifndef GRADER_H
#define GRADER_H

using namespace std;

#include <iostream>

class Grader {
  protected:
    int punt;
    string answers, id, stans;
  public:
    Grader(){
      answers = "112341423114322314231442314231223422";
      int i;

      char ans_arr[answers.length()];

      for (i = 1; answers.length(); i++){
        ans_arr[i] = answers[i];
      }
    }

    Grader(string ans) {
      answers = ans;
    }

    void Grade (string ans, string id, string stans) {
      int punt = 0;
      for (int i = 0; ans.length(); i++) {
        if (stans[i] == ans[i]){
          punt = punt + 2;
        } else if ((stans[i] != ans[i]) && (stans[i] != ' ')) {
          punt = punt - 1;
        }
      }

      cout << punt;
    }
};

#endif

//Main

#include <iostream>
#include "grader.h"
using namespace std;

int main() {

  string ans = "112341423114322314231442314231223422";

  Grader a(ans);

  string student_id = "12345";
  string student_ans = "11 3 1133 22322314231432211231 34 2";

  int punt = 0;

  a.Grade(ans,student_id,student_ans);

  return 0;
}

这样,我遇到了段错误。我了解我正在处理我不应该处理的记忆,但是我不知道如何使这项工作有效。

2 个答案:

答案 0 :(得分:3)

您的循环条件实际上不是条件。

来自w3schools

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

例如,当您的条件为ans.length()时,您的条件为i < ans.length()

由于ans.length()将始终具有相同的(正)值,因此它将被解释为需要继续的循环,并且i将继续增加。然后,类似ans[i]的东西实际上正在尝试在数组末尾之后查看内存,如果未将越界内存分配给您的应用程序,则会导致段错误。

答案 1 :(得分:0)

ans.length是36和stans.length is 35。以下代码从stans的外部读取。

for (int i = 0; ans.length(); i++) {
        if (stans[i] == ans[i]){

这是内存访问错误:

  Memory access error: reading from the outside of a memory block; abort execution.
  # Reading 1 bytes from 0x9df62c0 will read undefined values.
  #
  # The memory-block-to-be-read (start:0x9df6290, size:48 bytes) is allocated at
  #    unknown_location (report this ::244)
  #
  #  0x9df6290           0x9df62bf
  #  +--------------------------+
  #  | memory-block-to-be-read  |......
  #  +--------------------------+
  #                              ^~~~~~~~~~
  #        the read starts at 0x9df62c0 that is right after the memory block end.
  #
  # Stack trace (most recent call first) of the read.
  # [0]  file:/prog.cc::28, 13
  # [1]  file:/prog.cc::50, 3
  # [2]  [libc-start-main]

以后您可以使用此link来调试代码的段错误。只需单击“开始”即可在终端中生成并运行您的代码。

相关问题