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
  • 117,013
  • 19
  • 199
  • 247
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,074
  • 6
  • 41
  • 58
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
  • 29,989
  • 4
  • 56
  • 89