Hacking Book | Free Online Hacking Learning

Home

write java code to overflow heap and stack respectively

Posted by patinella at 2020-04-16
all

We know that in Java, you can use the keyword new to create Java objects. For example,

ArrayList list = new ArrayList();

In fact, after creating the above object, the new object will be stored in the heap memory in the JVM,

At the same time, the reference relationship of the object is stored in the method stack.

If you want to overflow the heap, you can create objects or large objects in a loop;

If you want stack overflow, you can call methods recursively. As the stack depth increases, the JVM maintains a long method call path,

Until there is not enough memory allocated, the stack overflows.

Therefore, the following simple code can be used to implement heap overflow and stack overflow.

public class Test { public void testHeap(){ for(;;){ ArrayList list = new ArrayList (2000); } } int num=1; public void testStack(){ num++; this.testStack(); } public static void main(String[] args){ Test t = new Test (); t.testHeap(); t.testStack(); } }

In addition, how to set the heap size of Java virtual machine: command line

Java – xms128m / / JVM occupies the minimum memory

– xmx512m / / maximum memory used by JVM

– XX: permsize = 64M / / minimum heap size

– XX: maxpermsize = 128M / / maximum heap size