Can someone tell me what is wrong with this code? I cannot find an error, but yet the compiler crashes everytime I execute it.

Convert.h

/*Dec to Bin and Hex to Dec*/
/*      Example            */
/*      Convert.h          */

/*Define the class*/
class Convert
{
      public:
             Convert();/*Constructor: default parameters*/
             void DecToBin(int); /*Dec to Hex*/ 
              void PrintResult();    
             ~Convert(); /*Destructor*/
      private:
              int maxSize; /*integer to store the maximum size of p*/
              int Result;
              int *pBits; /*Pointer to hold the int array of bits*/
              int iCount;
             
};

Conversion.cpp

/*Conversion.cpp, the implementation file*/

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

/*Default parameters of constructor*/
Convert:: Convert()
{
         
         pBits=0; /*Make it point to NULL*/
         iCount=0;
         Result=0;
         maxSize=255; /* This is the maxSize*/
         cout<<"Default Constructor was initialized"<<endl;
         
         
}


/*Dec to Bin*/
void Convert::DecToBin(int Results)
{
    Result=Results;
     if((Result>=1 && Result<=maxSize))
     {
                   while(Result>1)
                   {
                                  *pBits=Result%2; /*Serialise*/
                                  Result=Result/2; /*Divide*/
                                  pBits++; /*Point to the next location*/
                                  iCount++;
                                  cout<<*pBits<<" ";
                   }
                   
                   if(Result==1)
                   {
                                *pBits=1;
                    }
                                 
                 
      }
      
return;
}


Convert::~Convert()
{
          cout<<"Destructor executed"<<endl;
                 
                   }

Recommended Answers

All 2 Replies

You're using pBits, a pointer to something, without getting the memory for it with getmem(). Furthermore, you've defined 4 functions, but only have code for 1. Unless you haven't posted it all.

The problem with ur code is that u are ussign int *pbits without allocating memory to it using new () so a crash is for sure.

Try allocating some memory to it like

pBits = new int [1];        // allocates memory for one int element

Hope it helped,
bye.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.