+ 7

How to deallocate dynamic memory pointer return from a function?

I understand int* intPtr = new int; delete intPtr; char* charPtr = new char[10]; delete[] charPtr; however, if the dynamic pointer is returned from a function char* foo(){ char* charPtr2 = new char[20]; return charPtr2; } char* charPtr3 = foo(); cout << charPtr3 << endl; delete[] chatPtr3; //is this correctly deallocated the dynamic memory? how if I do it like this, cout << foo() << endl; //will the dynamic memory allocated in the function deallocate automatically? //if not, how to deallocate it?

5th Jul 2017, 6:10 PM
Heng Jun Xi
Heng Jun Xi - avatar
1 ответ
+ 4
delete charPtr3[] will work, because it is the same address. When you cout << foo() << endl; You are creating a memory leak. It will not be deallocated till your program exits.
5th Jul 2017, 6:37 PM
aklex
aklex - avatar