This is the right way to free up pointer memory in C ++

This is an example, I am amazed at whether this is the correct way to free up allocated pointer memory

char* functionTest() { char *a = new char[10]; return a; } int main() { char *b; b=functionTest(); delete[] b; return 0; } 

This is a very newbie, but still would like to clear my doubts. edited from delete to delete [] thanks @sharptooth. thanks in advance.

+4
source share
2 answers

Technically correct C ++ (from now on using editing with delete[] )

The code will compile and run without errors.

However, when creating C ++ code, you very rarely use the new [] and delete [], and you are much more likely to use a vector or use a string.

If you really want to allocate an array with a new [], you might want to use boost :: shared_array to control its deletion. Otherwise, you could use shared_ptr, but you would have to add your own debiter that calls delete [].

This method is called RAII (Resource Initialization is Initialization), which ensures that for any resource that you allocate, you already take care of its subsequent disposal, no matter what happens afterwards (including any exceptions that may be thrown).

+4
source

Here is a good technical description of the differences between delete and delete[] : http://blogs.msdn.com/b/oldnewthing/archive/2004/02/03/66660.aspx

0
source

Source: https://habr.com/ru/post/1339322/


All Articles