顯示具有 記憶體 標籤的文章。 顯示所有文章
顯示具有 記憶體 標籤的文章。 顯示所有文章

2010年9月15日 星期三

Java筆記-Finalize 終結物件

System.runFinalization()可用來請求執行finalize
在執行System.gc()時,也會執行finalize()
覆寫finalize()範例 ##ReadMore##

public class MyObject {
    static int count;
    MyObject() {
        ++count;
    }
    public static void main(String[] args) {
        MyObject obj1 = new MyObject();
        MyObject obj2 = new MyObject();
        MyObject obj3 = new MyObject();
        System.out.println("目前有" +count+ "個物件");
        obj2 = null;
        System.out.println("請求G.C.");
        System.gc();
        System.out.println("目前剩餘" +count+ "個物件");
    }
    protected void finalize() throws Throwable {
        --count;
        String tName = Thread.currentThread().getName();
        System.out.println("執行finalize()的是:" + tName);
    }
}

執行結果:
目前有3個物件
請求G.C.
執行finalize()的是:Finalizer
目前剩餘2個物件

Java筆記-System.gc() 記憶體釋放,回收垃圾物件

若程式碼指定物件為null,則會被garbage collector thread回收
請求調用Garbage Collection的函式
System.gc()和Runtime.getRuntime().gc()

2009年9月17日 星期四

C/C++筆記-memset動態配置記憶體

memset是在標準程式庫中,用組合語言撰寫
執行速度會較快且簡易,但只用在部分情況
memset是少見的記憶體配置方法

//calloc配置記憶體方法
foo_var = (struct foo*)calloc(3, sizeof(foo));

//等同於下列,此程式碼將結構內容清除為0
memset(foo_var, '\0', sizeof(foo)*3);
##ShowAll##

2009年9月11日 星期五

C/C++筆記-realloc重新配置記憶體空間

int *p;
p = (int *)malloc(sizeof(int) * 5);
p = (int *)realloc(p, sizeof(int) * 10); //將記憶體空間變大

C/C++筆記-malloc動態配置記憶體

/* 配置一個int大小的記憶體空間 */
int *p;
p = (int *)malloc(sizeof(int));

/* 配置一個struct大小的記憶體空間 */
struct ex{
  int a;
  char[2];
};
struct ex *p;
p = (struct ex *)malloc(sizeof(struct ex));
free(p); //釋放記憶體
##ShowAll##

2009年8月15日 星期六

C/C++筆記-calloc動態配置記憶體

與malloc功能相似,但會初始化為0,常用來配置陣列

/* 配置10 * int 大小的記憶體空間 */
int *p;
p = (int *)calloc(10, sizeof(int)); //需傳兩個參數

##ShowAll##
/