Why can't we allocate dynamic memory on the st

2020-07-09 08:07发布

Allocating stuff on the stack is awesome because than we have RAII and don't have to worry about memory leaks and such. However sometimes we must 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 only known at runtime (dynamic allocation).

Two questions:

  1. Why can't we allocate dynamic memory (i.e. memory of size that is only known at runtime) on the stack?

  2. Why can we only refer to memory on the heap through pointers, while memory on the stack can be referred to via a normal variable? I.e. Thing t;.

Edit: I know some compilers support Variable Length Arrays - which is dynamically allocated stack memory. But that's really an exception to the general rule. I'm interested in understanding the fundamental reasons for why generally, we can't allocate dynamic memory on the stack - the technical reasons for it and the rational behind it.

7条回答
一纸荒年 Trace。
2楼-- · 2020-07-09 09:00

Read a bit about Turing Machines to understand why things are the way they are. Everything was built around them as the starting point.

https://en.wikipedia.org/wiki/Turing_machine

Anything outside of this is technically an abomination and a hack.

查看更多
登录 后发表回答