What Do I Do If an Exception Occurs Because a Smart Pointer Is Used to Automatically Free Memory but the Destructor Is Not Empty?
Symptom
HIAI_DMalloc or HIAIMemory::HIAI_DMalloc is called to allocate memory for host-device or device-host data transmission. flag is set to MEMORY_ATTR_AUTO_FREE to automatically free memory. A smart pointer is used to store the address of the allocated memory, but no destructor is defined (the default destructor is called) or another destructor is called to free the memory (such as HIAI_DFree, which causes repeated memory freeing). As a result, the program becomes abnormal and memory leakage occurs.
Solution
The Matrix module automatically frees the memory. Therefore, set the destructor of the smart pointer to empty to resolve the problem.
The reference code is as follows:
* @ Allocates memory to be automatically freed. If a smart pointer is used, the destructor must be empty (the Matrix module automatically frees the memory). **/ int main() { // Uses DMalloc to allocate memory to be automatically freed. unsigned char* inbuf = nullptr; uint32_t bufferLen = 1080*1920; // The allocated memory is automatically freed. In this case, set flag to hiai::HIAI_MEMORY_ATTR::MEMORY_ATTR_ATUO_FREE. HIAI_StatusT getRet = hiai::HIAIMemory::HIAI_DMalloc(bufferLen, (void*&)inbuf, 10000); // getRet exception judgment // Stores the data to be transmitted in inbuf. The size of the data is bufferLen. // Assembles the engineTranData structure for sending data EngineTransNewT engineTranData; engineTranData->bufferSize = bufferLen; engineTranData->transBuff.reset(std::static_pointer_cast<uint8_t *> (inbuf), [](uint8_t *)(addr ) { // The destructor does not perform any operation. The Matrix module automatically frees the memory. If the destructor is not defined, the default destructor is called, causing an exception. // If another destructor such as HIAI_DFree is called, repeated memory freeing occurs, causing an exception. }); // Sends data to the peer end by calling SendData. HIAI_StatusT sendRet = SendData(DEFAULT_PORT,"EngineTransNewT",std::static_pointer_cast<void>(engineTranData)); // sendRet exception judgment }
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot