0
char* timeNew = _com_util::ConvertBSTRToString(cpi->getTime());
if(timeFirst == true)
    {
    strcpy(timeOld,timeNew);
    timeFirst = false;
    }

how can I initiliase timeold if I dont know what the size of character array returned by cpi->getTime is?

3 Answers3

1

Allocate memory for it based on length of timeNew:

delete[] timeOld;
timeOld = new char[strlen(timeNew) + 1];

or you could make timeOld a std::string and let it manage memory for you:

std::string timeOld;

timeOld = timeNew; // If timeNew is dynamically allocated you must still
                   // delete[] it when no longer required, as timeOld
                   // takes a copy of timeNew, not ownership of timeNew.

You can access the const char* using std::string::c_str() if really required.

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

Use strings where possible:

char *t= _com_util::ConvertBSTRToString(cpi->getTime());
std::string timeNew(t);
delete[] t;
if(timeFirst == true)
{
     timeOld=timeNew;
     timeFirst = false;
 }

if you don't have to manage the memory returned by teh function simply:

std::string timeNew(_com_util::ConvertBSTRToString(cpi->getTime()));
if(timeFirst == true)
{
     timeOld=timeNew;
     timeFirst = false;
 }
111111
  • 15,686
  • 6
  • 47
  • 62
0

If you have to use ConvertBSTRToString then use boost::scoped_array<char> or boost::shared_array<char> to ensure you get clean-up.

boost::shared_array<char> time;
time.reset( _com_util::ConvertBSTRtoString( cpi->getTime() );

automatically reallocates. No calls to delete or delete[] necessary.

CashCow
  • 30,981
  • 5
  • 61
  • 92