Returning pointer to an object from a method
Hello C++ experts, I am having a problem with system (microcontroller) stopping after some consecutive method calls, and I am pretty sure it is because of my incorrect pointer handling and corrupting heap memory.
So here is a method that I am calling
Code:
Message* MessageProcessor::processReceivedData(void)
{
uint8_t receivedByte;
if ( this->serialPort->available() )
{
this->serialPort->readBytes(&receivedByte, 1);
this->messageDeserialization->deserialize(receivedByte);
if ( this->messageDeserialization->isDeserialized() == MESSAGE_DESERIALIZATION_OK )
{
int8_t receieveBufferLen;
uint8_t* receieveBuffer;
int8_t retVal;
receieveBufferLen = this->messageDeserialization->getReceiveBufferLen();
receieveBuffer = new uint8_t[receieveBufferLen];
retVal = this->messageDeserialization->getDeserializedBuffer(receieveBuffer, receieveBufferLen);
Message message = this->messageDecoder->decode( receieveBuffer, receieveBufferLen );
return &message;
}
}
return NULL;
}
And from main.cpp I am calling this function and after call I delete pointer
Code:
int main(void)
{
.
.
.
while (true)
{
.
.
.
Message* message = NULL;
message = messageProcessor.processReceivedData();
if ( message != NULL )
{
if ( message->getDataType() == MESSAGE_DATA_TYPE_KEEP_ALIVE )
{
serialPortPc.writeString("I AM ALIVE\n\r");
}
serialPortPc.writeString("OK\n\r");
}
else
{
serialPortPc.writeString("NOK\n\r");
}
delete message;
.
.
.
}
}
I assume that the problem is because of the following reason:
1. after processReceivedData returns, it returns COPY of a pointer
2. after that I try to delete COPY of pointer, which doesn't do anything effective (I would need to return double pointer to this be effective ?)
I would rather prefer returning copy of an object, but than I do not know how to indicate error by return value (in my case returning NULL pointer in the last line of processReceivedData method.
I feel that my approach is completly incorrect since I am even returning pointer from my method, and making user having obligation to deal with memory (by calling delete).