看板 Programming 關於我們 聯絡資訊
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]
purpose:t_printf 的實作應該是關鍵吧..但作者沒給 124.8.128.11 04/06 10:26
bob123:t_printf應該只是用__attribute__讓編譯器 111.255.18.40 04/06 21:54
bob123:檢查printf的參數吧, 看了一下重點應該在 111.255.18.40 04/06 21:55
bob123:t_push()和t_pop()... 111.255.18.40 04/06 21:57
bob123:看了一下網站上的data-stack.c 感覺像是用 111.255.18.40 04/06 22:02
bob123:double linked list實作mem pool來當堆疊用 111.255.18.40 04/06 22:05
purpose:您說的是,我好像懂了。把 malloc 都改用 124.8.135.61 04/06 23:19
purpose:t_malloc 在配置空間的同時跟 Heap 管理器 124.8.135.61 04/06 23:20
purpose:一樣,用鏈結串列把最後於 t_pop 時要一起 124.8.135.61 04/06 23:21
purpose:free 的 heap blocks 串起來.. 124.8.135.61 04/06 23:21
EdisonX:p 大指的是這篇嗎? http://ppt.cc/aoSW 180.177.76.161 04/08 03:12