行为:内存操作错误或内存泄漏C++

Behavior: Bad operation on memory or Memory leak C++

本文关键字:内存 泄漏 C++ 操作 行为 错误      更新时间:2023-10-16

我是C++新手,我遇到了这样的错误

行为:内存

操作错误或内存泄漏: MyInteger::isPrime(int( (MyInteger.cpp:72( by: main (main.cpp:23(
at: 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";
    }

似乎您的函数isPrime是私有函数,无法在main((中调用这段代码对我有用

// Example program
#include <iostream>
#include <string>
using namespace std;
class MyInteger
{
   public: static bool isPrime(int);
};
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;
} 
int main()
{
    const string words[3][2] = {"not even", "even",
                                    "not odd", "odd",
                                    "not prime", "prime"};  
    int b=2;
    cout << "Integer "  << b << " is: ";
    cout << words[2][MyInteger::isPrime(b)] << ".n";
}

输出

Integer 2 is: not prime.