[英]Why am I getting segfault?
我是 C++ 的初學者,正在研究 class,它通過將學生的答案(“11 3 1133 22322314231432211231 34 2”)與答題卡(“112341423114322314231442323423212.323423212”)進行比較來給學生的答案打分我必須比較學生答案的每個值,如果它們匹配,則加 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;
}
有了這個,我得到了一個段錯誤。 我知道我正在處理 memory 我不應該處理,但我不知道如何進行這項工作。
您的 for 循環條件實際上不是條件。
來自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]
這樣的東西實際上試圖在數組結束后查看 memory,當超出范圍的 memory 沒有分配給您的應用程序時會導致段錯誤。
ans.length
是 36 和stans.length is 35
。 以下代碼從stans
的外部讀取。
for (int i = 0; ans.length(); i++) {
if (stans[i] == ans[i]){
這是 memory 訪問錯誤:
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]
您可以使用此鏈接在將來調試代碼的段錯誤。 只需單擊“開始”即可在終端中構建和運行您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.