看板Programming
标 题请教这篇Secure, Efficient and Easy C programming的原理
发信站椰林风情 (Thu Apr 5 23:50:42 2012)
转信站ptt!news.ntu!Palmarama
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]
1F:推 purpose:t_printf 的实作应该是关键吧..但作者没给 124.8.128.11 04/06 10:26
2F:推 bob123:t_printf应该只是用__attribute__让编译器 111.255.18.40 04/06 21:54
3F:→ bob123:检查printf的参数吧, 看了一下重点应该在 111.255.18.40 04/06 21:55
4F:→ bob123:t_push()和t_pop()... 111.255.18.40 04/06 21:57
5F:→ bob123:看了一下网站上的data-stack.c 感觉像是用 111.255.18.40 04/06 22:02
6F:→ bob123:double linked list实作mem pool来当堆叠用 111.255.18.40 04/06 22:05
7F:推 purpose:您说的是,我好像懂了。把 malloc 都改用 124.8.135.61 04/06 23:19
8F:→ purpose:t_malloc 在配置空间的同时跟 Heap 管理器 124.8.135.61 04/06 23:20
9F:→ purpose:一样,用链结串列把最後於 t_pop 时要一起 124.8.135.61 04/06 23:21
10F:→ purpose:free 的 heap blocks 串起来.. 124.8.135.61 04/06 23:21