2015年7月1日 星期三

[C筆記] 資料結構(Linklist)與動態記憶體Heap配置使用與釋放

前言:為了能夠動態配製記憶體,利用 malloc()來跟記憶體申請空間(HEAP),HEAP空間不像STACK空間會自己釋放掉,所以必須依靠free() 來釋放記憶體。




code sample:


#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 為了使用strdup

typedef struct island//<-命名             island 資料結構為linklist
        {
         char *name;
         char *open;
         char *close;
         struct island *next ; //遞回結構不能取消"命名" 
        }island;//<-別名
     
 island* creat(char* name)
 {
         island *i = malloc(sizeof(island));
         i->name = strdup(name); //請憶體配置name複本空間
         i->open = "09:00";
         i->close = "17:00";
         i->next =  NULL;
         return i;
         }
 void display(island *start)
 {
      island *i = start;
      for(;i!=NULL;i=i->next)
      {
        printf("name:%s open:%s - %s\n", i->name,i->open,i->close);
                             }
 }


void release(island *start)
{
     island *i = start;
     island *next = NULL;
   
     for(;i!=NULL;i=next)
     {
        next = i->next;
        free(i->name);
        free(i);                  
        }
     }

int main(int argc, char *argv[])
{
  island *start =  NULL;
  island *i =  NULL;
  island *next = NULL;
  char name[80];
  int count =0;
  for(;scanf("%79[^,],[\n]\n",name)== 1;i = next)
  {
      next =creat(name);
      if(start == NULL)
         start = next;
      if(i != NULL)
         i->next = next;
  }
  display(start);
  release(start);
  return 0;
}


main解說: 每新增一坐島嶼,就必須動態向記憶體申請一塊Heap空間(因為不知道有幾座島所以無法是先宣告在stack空間裡),建立島嶼的方法中 island* creat(char* name),藍色的兩行都是會向記憶體申請heap。


為什麼要用到strdup呢??原因在於

island* creat(char* name) c語言中不管設定指標或者陣列帶入函式都是送記憶體位置過去(就是指標)

island* creat(char* name) == island* creat(char name[])

換句話說當我們程式碼如果寫這樣   i->name = strdup(name); 紅色部分去除


islandA = creat(name);//假設name內容為a

islandB = creat(name);//假設name內容為b

此時  islandA 與 islandB 中的name 都會被修改成"b" 因為2者name都是指標指向真實記憶體位置

所以用strdup()在記憶體中另行存一個空間(heap),當不需要使用時,當然也必須做釋放的動作。

一個好的工程師除了程式不寫的臃腫不堪外,應該對記憶體的使用在腦海中有相當程度的對應圖。

trip.txt


輸出結果




沒有留言:

張貼留言