Free memory allocation

Is this a good practice? Or should I just replace the code block between the { and } function? It can be reused (I suppose), but my only motivation for this is to free colsum , since it is huge and it does not require me to free allocated memory.

  vector<double> C; { vector<double> colsum; A.col_sum(colsum); C = At*colsum; } doSomething(C); 
+2
source share
5 answers

Using brackets for automatic region variables works fine in my book, but as a rule, if you find yourself doing this a lot, especially several times in the same function, your function probably does too many different things and needs to be broken .

+13
source

Data for vectors is always dynamically allocated. Only accounting data is stored on the stack. Even if it weren’t, the memory allocation on the stack was essentially free. Allocation from the stack simply changes the value of the register on most architectures.

EDIT

As for dynamic release, it must be released at one point or another (in particular, at the end of the function). You do not lose anything by leaving the allocated memory until you want to allocate more, and this is not enough. Is the exact time when this release happens, really need to bother something before you encounter any problem?

/ EDIT

But what's the point? It seems that you are prematurely treating yourself with optimization.

If you want to reorganize your code, do it for the sake of clarity, not performance.

+5
source

The vector does not save memory on the stack. Only the vector object itself is stored here, which is not very large. Finding it like this, it causes destruction that will free the allocated memory.

Also, I'm not sure if it is specified in ISO, that the implementation should pull the subdirectory variable from the stack.

+3
source

As others have pointed out, vector memory is not allocated on the stack. If you want to free this memory at an early stage, the general idiom is:

 vector<double> C; vector<double> colsum; A.col_sum(colsum); C = At*colsum; std::vector<double>().swap(colsum); doSomething(C); 

This will create a temporary vector and replace the contents with your large vector. At the end of the instruction, the temporary will be destroyed and the memory will be released. You will be left with an empty vector.

Note that colsum.resize(0) and colsum.clear() do not need to free up available memory, and in many cases they do not assume that if the vector grows before this, then most likely it will do it again.

+3
source

If the internal code will be reused elsewhere, divide it into a function. If the internal code is called frequently (for example, in a loop), then it probably needs to be reorganized so that the vector is not constantly created and destroyed in the loop. Otherwise, I don’t think it’s bad practice to do what you suggested.

0
source

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


All Articles