Reputation: 665
i know that if i new some array i must delete it:
int *i=new i[10];
delete[] i;
what about static array like:
int i[100];
OR
int i[]={1,2,3,4};
should it be deleted?
asume the code bellow:
bool fu()
{
for(int i=0;i<100;i++
{
int j[]={1,2,3,4};
}
return 0;
}
is j[] goes away from RAM (after return 0;) or it remains there and make the RAM full after lots of iterations?
because i want to program on micro im a a little worry. thanx
Upvotes: 0
Views: 145
Reputation: 106066
what about static array like:
int i[100];
int i[]={1,2,3,4};
should it be deleted?
No... both static
data (which is used when definitions like these appear outside any function scope) and stack-based data (used for variables within a function) are automatically destructed (if needed) when the program terminates or scope exits respectively. Memory for static
variables does not need to be "released" explicitly by the program - the operating system will reclaim the memory when the program terminates. Stack memory is a bit like waves on a beach... as scopes are entered and exit, the same memory (think area on the beach) is used (covered) then released automatically, then reused....
bool fu()
{
for(int i=0;i<100;i++
{
int j[]={1,2,3,4};
}
return 0;
}
Here, j[]
is recreated on the stack - probably at the same address each time through the loop though the C++ Standard doesn't discuss such implementation details - but it may be reinitialised by recopying data from the constant (static) array where {1, 2, 3, 4} are stored for that purpose. (If the optimiser deduces you never change it, it might skip the reinitialisation, or even remove the stack variable and access the constant array values directly, or even remove the constant array and move specific values accessed into immediate values in the machine code opcodes - optimisers can do pretty much anything as long as it doesn't affect anything other than performance of the program).
Upvotes: 3
Reputation: 320
If you are declaring a "static" array as this,
static int i[100];
memory allocated for 100 integers remains through the life of the program. But for this,
int i[100]
the memory is getting free and goes out of stack (as this is local) while this goes out of scope.
Upvotes: 1
Reputation:
Take a look http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/ where you'll find explanations for your questions
Upvotes: 1
Reputation: 3345
You don't need to delete those. they are on the stack within the memory, not the heap and get cleared as soon as you leave their scope.
And in your example: j is cleared when you leave the loop.
Upvotes: 3