简体   繁体   English

C/Java 中的堆栈与堆

[英]Stack vs Heap in C/Java

Here's my understanding.这是我的理解。

In C programming, if I do int a then that a is created on stack and thus the memory is taken from stack.在 C 编程中,如果我做int a那么a是在堆栈上创建的,因此内存是从堆栈中取出的。 Heap plays no part here.堆在这里没有任何作用。

But if I do something like但如果我做类似的事情

int *a;
a=(int*)malloc(sizeof(int));

and dynamically allocate the memory, then the reference variable will be placed on stack, but the memory it points to will be on the heap.并且动态分配内存,那么引用变量会被放在栈上,但它指向的内存会在堆上。

Am I correct with my understanding?我的理解正确吗?

Now, I picked up this book on java that says现在,我拿起了这本关于 Java 的书,上面写着

Whenever you need an object, you simply write the code to create it by using new, and the storage is allocated on the heap when that code is executed.每当您需要一个对象时,您只需编写代码以使用 new 创建它,并在执行该代码时在堆上分配存储空间。

So there's no way of creating objects on Stack in Java?那么在 Java 中没有办法在 Stack 上创建对象吗?

I guess, the primitive data types can still be placed on stack, but I am concerned about the Objects.我想,原始数据类型仍然可以放在堆栈上,但我关心的是对象。

There is no way to create objects on the stack in Java. Java 无法在堆栈上创建对象。 Java also has automatic garbage collection, so you don't have any way of deleting objects. Java 还具有自动垃圾收集功能,因此您无法删除对象。 You just let all references to them go out of scope and eventually the garbage collector deals with them.你只是让所有对它们的引用超出范围,最终垃圾收集器处理它们。

That is correct.那是正确的。 Objects are stored on the heap.对象存储在堆上。 The stack contains primitive values like int and double (from local variables) and references to objects (again from local variables).堆栈包含原始值,如intdouble (来自局部变量)和对对象的引用(再次来自局部变量)。

The whole premise of your question is false: in Java you don't have any control over where the objects will be allocated.您问题的整个前提是错误的:在 Java 中,您无法控制对象的分配位置。 Some are indeed stack-allocated, but you'll never notice the difference.有些确实是堆栈分配的,但您永远不会注意到差异。

What is fundamentally different between Java and C is that in Java the value of a variable can never be the object itself, whereas in C the value can be the struct itself, with no indirection. Java 和 C 之间的根本区别在于,在 Java 中,变量的值永远不能是对象本身,而在 C 中,值可以是struct本身,没有间接性。 You can pass such structs by value to other functions and there is no equivalent of that in Java.您可以按值将此类结构传递给其他函数,而 Java 中没有等效的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM