前往
大廳
主題

C取時間和指標使用上的一些眉角

Yang | 2023-01-29 15:36:11 | 巴幣 0 | 人氣 161

接續之前寫的,C語言的sizeof(long)和下一個千禧蟲問題,這裡紀錄C取時間和指標使用上的一些眉角

參考網頁:

//1970/1/1開始經過多少秒
const time_t rawTime = time(NULL);

//轉成本地時間(本機作業系統時間)並使用struct tm資料格式
const struct tm *timeNowStruct = localtime(&rawTime);

//轉成Www Mmm dd hh:mm:ss yyyy格式
const char *timeNowStr = asctime(timeNowStruct);

struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */
};

參考網頁:

localtime和asctime回傳的是指標,會指向一個static的記憶體空間,因此非執行緒安全

如果要修改localtime或asctime的回傳值,應該要先把資料複製出來,再做調整

//複製純數值資料結構
struct tm timeNowStruct = *(struct tm *)localtime(&rawTime);

//把asctime複製到指定的char array
char buffer[32];
memset(buffer, 0, sizeof(buffer));

const char *_buf = asctime(localtime(&rawTime));
size_t len = strlen(_buf);

memcpy(buffer, _buf, len);


另外,因為localtime和asctime回傳的是一個static的記憶體空間,所以用完不需要釋放(free)


再參考網頁:

自行設計的方法,如果要回傳char *,
方法一是學asctime,宣告一塊static的記憶體空間
方法二是使用strdup,動態new一塊記憶體空間,但用完要記得釋放(free)

方法二是寫C最危險的地方,沒有garbage collection,要自己管理記憶體的使用,
記憶體用完忘記釋放,時間久了可能會塞爆機器,
已經釋放(free)的指標,如果沒管理好,不小心再釋放一次,程式會立刻當掉

方法三是在程式啟動時把會使用的記憶體都先宣告好,
程式運行中只會使用事先宣告好的記憶體空間,
方法三的細節之後補充
送禮物贊助創作者 !
0
留言

創作回應

更多創作