Rahul Rahul - 24 days ago 9
C++ Question

cannot safe delete LPTSTR allocation

CCustomDateTime::CCustomDateTime()
{
LPTSTR result = new TCHAR[1024];
time_t _currentTime_t = time(0);
tm now;

localtime_s(&now, &_currentTime_t);
_tasctime_s(result, _tcslen(result), &now);

_currentTime = result;
delete[] result; //error occurs here
}


CCustomDateTime::~CCustomDateTime()
{

}

__int64 CCustomDateTime::CurrentTimeAsInt64()
{
return _currentTime_t;
}

LPTSTR CCustomDateTime::CurrentTimeAsString()
{
return _currentTime;
}


I am unable to figure out the safest place to call delete[] on result.

If
delete[]
is ignored everything is fine but otherwise error occurs

Answer

There are a few problems with your code that I can see:

  1. You don't check any of the function calls for errors. Don't ignore the return value. Use it to check for errors.
  2. The second argument to _tasctime_s is the number of elements in the buffer provided. In other words, 1024. But you pass _tcslen(result) which is the length of the null-terminated string. Not only is that the wrong value, but result is at that point not initialised, so your code has undefined behaviour.
  3. You assign a value to _currentTime, and then immediately delete that memory. So, _currentTime is a stale pointer. Any attempt to read from that memory is yet more undefined behaviour.

I don't want to tell you what your code should be, because you have only given us a tiny window into what you are trying to achieve. Dynamically allocating a fixed length array seems pointless. You may as well use automatically allocated storage. Of course, if you do want to return the memory to the caller, then dynamic allocation makes sense, but in that case then surely the caller would be responsible for calling delete[]. Since this code is clearly C++ I have to wonder why you are using raw memory allocation. Why not use standard library classes like std::string?

Looking at your update to the question, you could deallocate the memory in the destructor of your class. Personally though, I would recommend learning about the standard library classes that will greatly simplify your code.