c++ - Why can't we allocate dynamic memory on the stack? -
It is great to allocate goods to the stack because we have an RAI and you do not have to worry about memory leaks. And though sometimes we have to allocate on the heap:
-
If the data is really big (recommended) - because the stack is small.
-
If the size of the data to be allocated is known only in the runtime (dynamic allocation).
Two questions:
-
We can not allocate dynamic memory on the stack (i.e. memory size which is only available in runtime Is known)?
-
Why can not we just see the memory on the heap, through the points, while on the stack can the memory be sent through normal variables? To wit.
Thing T; . Edit: I know that some compilers support variable length arrays - which dynamically allocate stack memory but this is actually an exception to the general rule. I am interested in understanding the basic reasons for this, generally, we can not allocate dynamic memory on the stack - the technical reason for this and the rational behind it
Why can not we allocate dynamic memory on the stack (i.e. size memory which is known only in runtime)?
This is more complicated to achieve this. The size of each stack frame is burned to your compiled program so that the executable ready to work can be seen as the result of the type of instructions. For example, the layout and whatnot of your function-local variable are really hard-coded into your program through the addresses and memory addresses mentioned in the low-level assembly code in your program: "Variables" are actually executable Are not present in Between compilations, these "variables" make this process very complex to run the size and shape of changes, although this is not entirely impossible (as you have found, non-standard variable-length arrays < / Em>). / P>
Why can we only see the memory on the heap through pointers, while the memory on the stack can be referenced through the normal variable
This is just the result of a syntax, the "normal" variables of C ++ are either automatic or static storage durations. The designer of the language may be made it technically so that you can write something like
Thing t = new thing and just write the code all day
t Use, but they did not; Again, it would have been more difficult to implement. How do you differentiate between different types of things, then? Remember, your compiled executable has to remember to auto-destruct in one way, not the other.
I would love to go to the details of the exact details and why this is not the problem, because I believe that after you are here, unfortunately, my knowledge of assembly is very limited.
-
Comments
Post a Comment