There is a piece of code in the program:
while (true) { char value[len+1]; //какие-то операции с переменной value } Is there a memory leak if you don’t reset the value variable at the end of the loop operations?
There is a piece of code in the program:
while (true) { char value[len+1]; //какие-то операции с переменной value } Is there a memory leak if you don’t reset the value variable at the end of the loop operations?
Not.
Your value array belongs to the automatic memory class. It will be destroyed without your participation.
Now about when leaks may occur. Memory leaks may appear when you start allocating memory manually:
char *value = new char[len+1]; In my example, the value variable of the type "pointer to char " is declared. This variable indicates the area of memory that you are responsible for freeing.
To avoid a leak, you need to delete what value indicates:
delete[] value; Thus, the code will look like this:
void foo(int len){ char *value = new char[len+1]; //... delete[] value; } PS : By the way, your code should look something like this. Because in C ++, the size of the array must be known at compile time. If your compiler chews on char value[len+1] , then this does not mean that the other will do the same.
const int len , then nothing criminal. If not, then you are taught mistakes. In general, you need to use std::vector . You, probably, have not reached this yet, this is so for the future. - yrHeTaTeJlbThere is no dynamic allocation of memory, so about any leakage is out of the question. Although the char value[len+1] will only work on gcc.
len announcement is not presented, it’s premature to talk about VLA. This may well be a compile time constant. - αλεχολυτI remember how the teacher asked whether it was worthwhile to take out variable declarations before the cycle. The teacher said that he didn’t need it, I don’t remember whether he argued.
In all codes that are written by smart people (large corporations), it is also clear that the variables are declared in the body of the cycle.
My logic says: why allocate a memory area every time, it also takes some time for the machine, but I do everything))
Perhaps the "smart" compilers, all new variables in the loop as they themselves optimize the code, I do not know.
Source: https://ru.stackoverflow.com/questions/705698/
All Articles