【发布时间】:2019-04-21 15:53:21
【问题描述】:
我是 C++ 新手,我正面临这样的错误:
行为:内存操作错误或内存泄漏: MyInteger::isPrime(int) (MyInteger.cpp:72) by: main (main.cpp:23)
在:MyInteger::isPrime(int) (MyInteger.cpp:59)
这是什么意思,我该如何解决?我尝试使用valgrind,但对于新生来说似乎有点复杂。
//MyInteger.cpp
bool MyInteger::isPrime(int z){
int i,flag1;
if(z == 1){
flag1 = 1;
}
for(i = 2; i < z; i++){
if(z % i == 0)
{
flag1 = 1;
break;
}else flag1 = 0;
}
if(flag1 == 1){
return false;
}else return true;
}
//MyInteger.hpp
class MyInteger{
public:
static bool isPrime(int);
};
//main.cpp
int main{
const string words[3][2] = {"not even", "even",
"not odd", "odd",
"not prime", "prime"};
..............................
..............................
...............................
cout << "Integer " << b << " is: ";
cout << words[0][MyInteger::isEven(b)] << ", ";
cout << words[1][MyInteger::isOdd(b)] << ", ";
cout << words[2][MyInteger::isPrime(b)] << ".\n";
}
【问题讨论】:
-
我在这里看不到
static关键字,我在这里看不到指针。所以它绝对是由这个函数的调用者引起的,而不是这个函数。你最好调试一下 -
“我不能把整个代码放在这里”——没有人想要完整的代码。我们想要的是minimal reproducible example。一个最小的示例通常是您专门为提出问题而创建的新程序。
-
@JesperJuhl 明白了
-
@NguyễnSanhĐìnhAnh 我确实编辑了这个问题,请你看一下。我在 main.cpp 文件中调用它
-
words看起来像一个数组?在这种情况下, aboce 调用没有真正意义,除非您将要打印的文本存储在其中,例如words[0][0]包含“数字是奇数”。你初始化这个数组吗?请提供足够的代码来帮助您。
标签: c++ memory-leaks