0
About memory, before we allocate something with 'new' all values are stored, actually where? I mean we allocate some memory just in case we run out of space in our program?
8 Respostas
+ 2
You allocate memory, if you don't know the necessary size of memory. With "new" you allocate memory within the 'heap'. This is not needed for standard variables where you know the size. They are automagically allocated for you in 'stack'.
+ 2
@Tensa: Not to be nitpicky, you are 90% there. Still, you can allocate a known amount of memory on the heap. Stack and heap are both dynamic memory, the major difference is that you have free control over the heap and over stack you don't.
+ 1
@Lukasz: You do not have control over where all of the memory is allocated. The compiler will write the machine code such that all local variables are "automagically", as Tensa said, put on the stack and "automagically" removed, when you leave the code part for which it was allocated. This is helpful as you don't have to do it yourself as a programmer which means that the allocation and deallocation of that local memory won't have any errors as would occur if the programmers had to do it manually.
0
why just not use heap instead of stack, when u can't control it? sorry for my lack of knowledge and never ending questions :x just learning.
0
em let me see if I understand it properly.
for example: part program uses some variable (locacl) it's stored in stack when program move to another part this variable is deleted and I can't use it anymore.
and other thing
part program uses allocated variable ( in heap) it moves it into stack and uses it. then moveing into another part deleted stack but heap stays.
am I right or am I wrong? :x
0
Yeah, pretty much. :-) Just one note to make sure this is not something in your mental model.
A variable is either on stack *or* heap. Moving a variable to the heap is not a standard operation and means manually copying it to the heap.
0
yeye I'm new in this environment :D I wanted 2 say it duplicates pretty much copy :) but tux for your patience explaining things
0
@Lukasz: Thx, my pleasure. :-)