Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

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.

So there's no way of creating objects on Stack in Java?

I guess, the primitive data types can still be placed on stack, but I am concerned about the Objects.

like image 296
Kraken Avatar asked Sep 19 '25 05:09

Kraken


1 Answers

There is no way to create objects on the stack in Java. Java also has automatic garbage collection, so you don't have any way of deleting objects. You just let all references to them go out of scope and eventually the garbage collector deals with them.

like image 178
Ted Hopp Avatar answered Sep 20 '25 20:09

Ted Hopp