[英]C++: This code compiles, but throws Run-Time Check Failure #2 - Stack around the variable 'num' was corrupted. occurred
[英]Run-Time Check Failure #2 - Stack around the variable 'e' was corrupted. occurred
#include<iostream>
#include <list>
using namespace std;
class Euler {
private:
int korifes = 0;
int akmes = 0;
int* pinakas[];
public:
void print() { cout << *pinakas[0]; return; }
Euler(int korifess, int akmess);
~Euler() { delete[] *pinakas; }
void addAkmes(int kor1, int kor2);
};
Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess) {
*pinakas = new int(korifes);
*pinakas[0] = 89;
}
int main() {
Euler e(2, 1);
e.print();
}
運行時檢查失敗 #2 - 變量“e”周圍的堆棧已損壞。 發生...我在我的代碼中找不到錯誤的地方。
您的代碼中有許多錯誤,都與pinakas
成員變量的性質有關。 就目前而言,您將其聲明為指針數組(指向int
),此外,您正在使用“靈活” arrays (空[]
)的非標准語法。
我通常不只是粘貼“固定”代碼作為答案,但在這種情況下,該代碼(在我進行更改的地方添加了\\\
注釋)可能是幫助您的最簡潔的方式。
雖然,正如這里的許多人無疑會指出的那樣,最好避免使用“原始”指針以及new
和delete
運算符,而是使用std::vector
容器。
#include <iostream>
#include <list>
//using namespace std;/// This is considered 'bad practice' by many programmers
using std::cout;/// Just use the aspect of the STL that you need!
class Euler {
private:
int korifes = 0;
int akmes = 0;
int* pinakas;/// This will point an 'array' of integers
public:
void print() {
cout << pinakas[0]; return;/// No longer any need for the dereference (*)
}
Euler(int korifess, int akmess);
~Euler() {
delete[] pinakas;/// No need for the dereference (*)
}
// void addAkmes(int kor1, int kor2);/// You haven't provided an actual definition for this, but your never use it!
};
Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess)/// NOTE: Members are initialized in DECLARATION order!
{
pinakas = new int[korifes];/// Use "[]" (not "()") to allocate an array!
pinakas[0] = 89;/// No need for the dereference (*)
}
隨時要求任何進一步的澄清和/或解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.