`
ydcworld
  • 浏览: 23515 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Stack and Heap

    博客分类:
  • java
 
阅读更多
Read a good article about Heap and Stack,so to share with each other.
In order to have a deep understanding of the Object Oriented Programming in Java or any other OOP language (like C#) you must know how things are managed internally by the Java process and by the JVM. Of course Java syntax and Java implementations of OOP principles are important but you will have a more clear image about the application resources, memory, performance, argument passing, threads and garbage collection if you put questions beyond How I do that ? or How I write that ?. The real questions should be How or Why it is happening like this ? (of course, at some point you should stop and move forward).

In this post I will describe how the application variables are managed, regarding where they are stored (Stack or Heap) and for how long.


Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents

What is the Stack and the Heap
Keeping things simpler (if you know some assembler background you will see that this is a superficial approach) your application is processing data by storing it into memory areas in Random Access Memory. These areas are called:

Stack:

a memory space reserved for your process by the OS;
the stack size is fixed and it is determined in the compiler phase based on variables declaration and other compiler options;
it is important to establish that the stack is limited and its size is fixed (one the process has started, it can’t change the stack size);
most of the time, the stack it is used to store functions/methods variables (input arguments and local variables).
each method has its own stack (a zone in the process stack), including main, which is also a function.
a method stack exists only during the lifetime of that method: from the calling moment until the return moment;
Heap:

a memory space managed by the OS and used by processes to get additional space at run-time;
this area it is a global, meaning that any process can use it (of course, processes can’t read or write in another process Heap reserved area);
the role of this memory is to provide additional memory resources to processes that need that supplementary space at run-time (for example, you have a simple Java application that is constructing an array with values from console);
the space needed at run-time by a process is determined by functions like new (remember, it the same function used to create objects in Java) which are used to get additional space in Heap.
What is stored in Stack and in Heap
Based on previous rules, let’s analyze this simple Java application:
class Student{
    int age;               //instance variable
    String name;     //instance variable
 
    public Student()
    {
        this.age = 0;
        name = "Anonymous";
    }
    public Student(int Age, String Name)
    {
        this.age = Age;
        setName(Name);
    }
    public void setName(String Name)
    {
        this.name = Name;
    }
}
 
public class Main{
	public static void main(String[] args) {
            Student s;                   //local variable - reference
            s = new Student(23,"Jonh");
            int noStudents = 1;          //local variable
	}
}

In order to determine the minimum space (because we focus only on the important elements and we keep things as simple as possible) let’s analyze the Stack requirements. In the next paragraph I describe each method stack separately but in the end all these are placed on the same stack, the application stack.

We start with the main method because for a Java process everything begins and ends with main. The main local variables, or variables stored on its Stack are:

the args reference (it is an array of Strings);
the Student reference, named s;
the integer (4 bytes) value, named noStudents;
The default constructor local variables are:

the current created object reference, named this;
that’s all (remember: the object and its values are stored in Heap).
The second constructor, the one with arguments, local variables:

the reference of the current created object, named this;
the input argument, Age, an integer value
the input argument, Name, a String reference
The setName method local variables are:

the calling object reference, named this; (remember: each non-static class method it is called by an object and that object reference is passed to the method as this)
the input argument, Name, a String reference
As I said earlier, all these methods stacks are in fact, parts of a single applications stack. Each part exists during the function lifetime. If you analyze the order in which these methods are called you can define a bigger picture – the process call stack.

For the previous example, when the constructor with arguments it is executed, the call stack looks like this:

As you can see, from the previous image, the call stack is generated by all the active methods. Because the main method is the process entry point, it is the first method on the call stack. After this moment, each time a method is called, it will be placed on the call stack.

For the previous example, the call stack has the maximum size when it is called the setName method from the Student constructor.

In Heap there are stored all the values that are created using new operator, meaning mostly object values. So, for the previous example, the references are stored on the method stack and the objects are stored in Heap:

In the previous image, there are described the methods local variables, which are stored on their stack. Also, you can see that objects values (the Student and the String) are stored in Heap.

The Heap values are created by:

the Student memory area in Heap is created by calling the new operator and the class constructor;
the String value is created during the object initialization inside the class constructor.
What is the lifetime of variables from Stack and Heap
The general rule regarding the lifetime of variables is that they exist at least for the time you need them.

For stack variables, because they are on the method stack, they exist as long as the method is executed. Because main method is a special method (the process starts and ends with main) its local variables exist for the entire execution of the process. For other methods, their stack exists only from the moment we call the method until it ends (with a return or because of an exception).

The values in Heap (object values) exist as long as we have a reference that has the address of that memory area in Heap. If the Heap memory area can’t be reached through a reference (the reference does’t exist or it has another value/address), the Garbage Collector will release that space. (more on Garbage Collector in next tutorial).

Other types of variables, like the class static attributes, are managed in the same way,with the difference that they are stored on the process stack, before using that stack for methods stacks.
分享到:
评论

相关推荐

    Understanding and Using C Pointers 原版pdf by Reese

    The stack and heap are areas of memory used to support functions and dynamic memory allocation, respectively. Pointers are complex enough to deserve more in-depth treatment. This book provides that ...

    startup_armv7-m.7z

    Specifying stack and heap using the scatter file The ARM C library provides multiple implementations of the function __user_setup_stackheap(), and can select the correct one for you automatically ...

    Hands-On Data Structures and Algorithms with Rust.epub

    In this chapter, we think about stack and heap memory. Chapter 4, Lists, Lists, and More Lists, covers the first data structures: lists. Using several examples, this chapter goes into variations of ...

    Hands-On Penetration Testing on Windows - 2018 pdf 5分

    We'll work through core network hacking concepts and advanced Windows exploitation techniques, such as stack and heap overflows, precision heap spraying, and kernel exploitation, using coding ...

    Chapter 9. The Stack and the Heap

    We program in high-level languages for ... And perhaps we prefer solving problems strictly through an abstract quasi-mathematical algorithmic language without taking machine architecture into account.

    Bounds Checker6.01 for Delphi

    BoundsChecker automatically pinpoints static, stack and heap memory errors, and resource leaks. Unlike ordinary memory-checking tools, BoundsChecker validates the latest Windows APIs including ...

    The Run-time Heap and Stack

    在IT领域,尤其是在操作系统与编程语言的运行时环境中,“运行时堆和栈”(The Run-time Heap and Stack)是理解程序内存管理的核心概念。本文旨在深入解析这一主题,结合提供的部分文档内容,详细阐述堆和栈的区别...

    IBM heapdump analyzer

    在一些平台上,在有些情况下,javacore也被称为javadump,它包含jvm和应用程序相关的在特定时刻的一些诊断信息,如操作系统,应用程序环境,线程,native stack本地堆,锁,和内存的信息。在生成heapdump文件的时候...

    英文原版-Problem Solving and Program Design in C 7th Edition

    In later chapters, students learn to implement fundamental data structures such as lists, stacks, queues, and trees in a language that fosters their understanding of stack- and heap-dynamic memory ...

    Z-Stack Home 1.2.0中预编译宏定义详细解释2

    - **Unique and Global Link Key Type Configuration**:这些宏定义允许用户配置独特的或全球性的链接密钥类型,从而增强了系统的灵活性和安全性。 - **Backwards Interoperability**:这一节介绍如何确保旧版本的...

    Selected.Topics.in.Cplusplus.15117

    C++ has stack memory and heap memory. You need to control where you want to put your objects. It has constructors and destructors. You need to know when and how they are called. Then it has multiple ...

    数据结构常用算法c++实现

    Stack Binary Heap Fibonacci Heap Priority Queue (list based) Bubble sort Selection sort Insertion sort Radix sort Quick sort Merge sort Heap sort Double linked list Skip list Self-organized linked-...

    JVM内核架构--JVM规范

    Whenever a method is invoked a new stack frame is added to the stack and corresponding frame is removed when its execution is completed. Native method stack: holds the state of each native method ...

    Problem.Solving.in.Data.Structures.and.Algorithms.Using.Cplusplus.epub

    We will be looking into a linked list, stack, queue, trees, heap, hash table and graphs. We will be looking into sorting, searching techniques. Then we will be looking into algorithm analysis, we ...

    Gray Hat Hacking, Second Edition

    Learn the basics of programming, stack operations, buffer overflow and heap vulnerabilities, and exploit development Test and exploit systems using Metasploit and other tools Break in to Windows and...

    Packt.Mastering.Csharp.and.NET.Programming

    - **The Stack and the Heap**: Explains the difference between stack-allocated and heap-allocated memory and their respective uses. - **Garbage Collection**: Discusses how the .NET runtime ...

    CC2530 document

    Upgrading To Z-Stack v2.0.0 Upgrading To Z-Stack v2.1.0 Upgrading To Z-Stack v2.4 ...Z-Stack Monitor and Test API Z-Stack API Z-Stack Compile Options 802.15.4 MAC API OSAL API HAL Driver API ...

    解决ads工程转到MDK(keil)可能出现的error

    以及“scatter-load file declares no heap or stack regions and __user_initial_stackheap is not defined”错误,这表明链接器未能找到`Main`符号或堆栈和堆的定义。解决此问题,通常在完成步骤1后,如果代码中...

Global site tag (gtag.js) - Google Analytics