請教這篇Secure, Efficient and Easy C 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]
推
04/06 10:26, , 1F
04/06 10:26, 1F
推
04/06 21:54, , 2F
04/06 21:54, 2F
→
04/06 21:55, , 3F
04/06 21:55, 3F
→
04/06 21:57, , 4F
04/06 21:57, 4F
→
04/06 22:02, , 5F
04/06 22:02, 5F
→
04/06 22:05, , 6F
04/06 22:05, 6F
推
04/06 23:19, , 7F
04/06 23:19, 7F
→
04/06 23:20, , 8F
04/06 23:20, 8F
→
04/06 23:21, , 9F
04/06 23:21, 9F
→
04/06 23:21, , 10F
04/06 23:21, 10F
推
04/08 03:12, , 11F
04/08 03:12, 11F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):
Programming 近期熱門文章
PTT數位生活區 即時熱門文章