- 论坛徽章:
- 0
|
本人是初手, 看一些源程序,有些关于struct中的内存分配问题,不明白:
pg_dump.h
typedef struct SimpleStringListCell
{
struct SimpleStringListCell *next;
char val[1]; /* VARIABLE LENGTH FIELD */
} SimpleStringListCell;
typedef struct SimpleStringList
{
SimpleStringListCell *head;
SimpleStringListCell *tail;
} SimpleStringList;
|
pg_dump.c
#include "pg_dump.h"
static SimpleStringList schema_include_patterns = {NULL, NULL};
void
simple_string_list_append(SimpleStringList *list, const char *val)
{
SimpleStringListCell *cell;
/* this calculation correctly accounts for the null trailing byte */
// 以下语句有点费解
cell = (SimpleStringListCell *)
pg_malloc(sizeof(SimpleStringListCell) + strlen(val));
cell->next = NULL;
strcpy(cell->val, val);
if (list->tail)
list->tail->next = cell;
else
list->head = cell;
list->tail = cell;
}
int
main(int argc, char **argv)
{
.....
simple_string_list_append(&schema_include_patterns, "abcdefg");
....
}
|
有2个问题:
1. 结构SimpleStringListCell有一成员 char var[1]竟能存储不定长的字符,即对它的内存分配有点费解
cell = (SimpleStringListCell *)
pg_malloc(sizeof(SimpleStringListCell) + strlen(val));
2. 在struct中用malloc分配了内存, 程序结束需要手工释放内存吗? 我在他的程序里没看到free语句
请多多指教,谢谢.
[ 本帖最后由 trainee 于 2009-5-25 16:02 编辑 ] |
|