Why do we need to create an object in heap?

2019-08-16 05:51发布

why can we use the stack for all our needs?

NOTE: it will be very good if you give an example while explaining because it is easier to understand with examples.

sorry for bad English.

1条回答
干净又极端
2楼-- · 2019-08-16 06:34

In practice the call stack is limited and small. The typical limit is a few megabytes. In contrast, you could often allocate gigabytes in heap memory.

(on some systems, you might configure the system to have a larger stack; but you need to tell your users if you need that)

Also, and most importantly, the call stack is a stack, so has a LIFO (last in first out) discipline. In many cases, you want to release objects in an order unrelated to their allocation or just in a "first allocated, first destroyed" order (and that is impossible on a stack).

Consider reading something about garbage collection, e.g. the GC handbook. It teaches you useful concepts and terminology about dynamic memory allocation (even for C programs with manual memory management). Read also about the virtual address space of your process (se also this answer, at least for Linux).

Another advantage of dynamic memory allocation is that the same executable can run on various computers (with various resources, in particular different amount of RAM), but won't be able to process the same amount of data. If you had to allocate all the memory statically, this would not be the case (e.g. a C program with 50 gigabytes of static data could not even start on my laptop).

查看更多
登录 后发表回答