請教這篇Secure, Efficient and Easy C programming的原理

看板Programming作者時間13年前 (2012/04/06 02:01), 編輯推噓4(407)
留言11則, 3人參與, 最新討論串1/2 (看更多)
http://irccrew.org/~cras/security/c-guide.html "Secure, Efficient and Easy C programming" 這篇文章看大意 是在介紹利用記憶體佈局中的 stack 來達成不需手動經由malloc / free 動態配置/回收記憶體的技巧,但想必是我的 C 語言學得太差,看不懂他範例程式 是如何使用到 stack。如果有 C 達人讀過這篇文章,能否為在下解惑,說明一下 作者用了什麼方式來操控 stack 在自己的程式中模擬「動態記憶分配」的功能, 謝謝 // 以下是網頁上的第一個程式,我讀得一頭霧水,看不出「動態分配」在哪? /* asprintf()-like functon, but allocates the memory from data stack */ const char *t_printf(const char *fmt, ...) __attribute__((format (printf, 1, 2))); void client_input(struct client *client) { const char *cmd; int i; cmd = read_command(client); if (cmd == NULL) return; if (strcasecmp(cmd, "status") == 0) { time_t now = time(NULL); client_send(client, t_printf("Time: %s", ctime(&now))); client_send(client, t_printf("Clients: %u", clients_count)); for (i = 0; i < 10000; i++) { /* without an extra stack frame here, we'd allocate the t_printf() 10000 times before freeing them all. That's probably not be very good. */ t_push(); client_send(client, t_printf("%d: %u", i, stuff[i])); t_pop(); } } else { client_send(client, t_printf("Unknown command: %s", cmd)); } } void main_loop(void) { unsigned int i, id; fd_set rfds; if (select(max_fd, &rfds, NULL, NUL, NULL) <= 0) return; for (i = 0; i < clients_count; i++) { if (FD_ISSET(clients[i].fd, &rds)) { id = t_push(); client_input(&clients[i]); if (t_pop() != id) { /* we could simply call the missing t_pop()s, but this usually indicates a problem which we want to know. for example we might have leaked it inside a for loop which caused unnecessarily large memory usage. */ panic("missing t_pop()"); } } } } -- ☆ [Origin:椰林風情] [From: host-219-70-179-157.dynamic] [Login: 3] [Post: 0]

04/06 10:26, , 1F
t_printf 的實作應該是關鍵吧..但作者沒給
04/06 10:26, 1F

04/06 21:54, , 2F
t_printf應該只是用__attribute__讓編譯器
04/06 21:54, 2F

04/06 21:55, , 3F
檢查printf的參數吧, 看了一下重點應該在
04/06 21:55, 3F

04/06 21:57, , 4F
t_push()和t_pop()...
04/06 21:57, 4F

04/06 22:02, , 5F
看了一下網站上的data-stack.c 感覺像是用
04/06 22:02, 5F

04/06 22:05, , 6F
double linked list實作mem pool來當堆疊用
04/06 22:05, 6F

04/06 23:19, , 7F
您說的是,我好像懂了。把 malloc 都改用
04/06 23:19, 7F

04/06 23:20, , 8F
t_malloc 在配置空間的同時跟 Heap 管理器
04/06 23:20, 8F

04/06 23:21, , 9F
一樣,用鏈結串列把最後於 t_pop 時要一起
04/06 23:21, 9F

04/06 23:21, , 10F
free 的 heap blocks 串起來..
04/06 23:21, 10F

04/08 03:12, , 11F
p 大指的是這篇嗎? http://ppt.cc/aoSW
04/08 03:12, 11F
文章代碼(AID): #1FVTtUkc (Programming)
文章代碼(AID): #1FVTtUkc (Programming)