If I want to allocate a struct
in C,
#include<stdio.h>
typedef struct container {
int i;
} Container;
int main() {
Container *ptr_to_container;
ptr_to_container = (Container *) malloc(sizeof(Container));
ptr_to_container->i = 10;
printf("Container value: %d\n", ptr_to_container->i);
free(ptr_one);
return 0;
}
I explicitly have to call malloc
and free
. How does a VM go about doing this?
If I create an object in Java,
public class Container {
public int i;
public static void main(String[] args) {
Container container = new Container();
container.i = 10;
System.out.println("Container value: " + container.i);
}
}
Garbage Collectors account for the freeing, but not the allocating. How does the JVM allocate the amount of data needed? Does it call malloc
or another memory management implementation?
How does the JVM know the amount of data needed? Does it add up the length of all the fields?