0

I have a simple class aClass:

class aClass
{
public:
    aClass(int size)
    {
        condition = new bool[size];
    }
    ~aClass()
    {
        delete condition;
    }
    bool getCondition(int i) const
    {
        return condition[i];
    }

    void setCondition(bool* condition, int i)
    {
        *(this->condition + i) = *condition;
    }
private:
    bool* condition;
};

In fact I defined a bool pointer and using constructor to allocate memory.

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

int main()
{
    aClass tempVar(10);
    bool *pC;

    for (int i = 0; i < 10; i++)
    {
        *pC = 0;
        tempVar.setCondition(pC, i);
    }
   for (int i = 0; i < 10; i++)
   {
         cout  <<  tempVar.getCondition(i);
   }
    return 0;
}

I do not know what is the problem in this code.

I used gcc version 4.6.3 to compile the code.

user1436187
  • 3,252
  • 3
  • 26
  • 59

2 Answers2

4

You are trying to dereference pC although you never initialized the pointer. Probably pC should have type bool, not bool*, at the same time *pC = 0 should likely be pC = 0 and setCondition should likely take bool not bool*.

You delete although it should be delete[], see here why: delete vs delete[]

Your code will try to delete allocated memory twice if an instance of aClass is copied somewhere. See Rule of three.

You should use std::vector instead of the manually allocated array.

Community
  • 1
  • 1
2

There are two mutually exclusive problems here:

  1. You haven't initialized pC. Do this:

    int main() {
        ⋮
        bool * pC = new bool;
        ⋮
        delete pC;
    }
    

    Actually, raw pointers aren't such a good idea, so this is better:

        std::unique_ptr<bool> pC(new bool);
        // No delete required.
    
  2. setCondition() doesn't need a pointer parameter at all:

    class aClass {
        ⋮
        void setCondition(bool cond, int i) {
            condition[i] = cond;
        }
        ⋮
    };
    
    int main() {
        ⋮
        for (int i = 0; i < 10; ++i) {
            tempVar.setCondition(false, i);
        }
        ⋮
    }
    
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365