C语言中带有日期的奇怪行为

C语言中带有日期的奇怪行为,c,date,pointers,C,Date,Pointers,以下是我所拥有的: struct test_date { time_t t; pid_t pid; }; int main(int argc, char *argv[]) { dates = malloc(CHILDREN_LIMIT * sizeof(struct test_date*)); // an array declared static of type struct test_date //... later struct test_date

以下是我所拥有的:

struct test_date {
    time_t t;
    pid_t pid;
};

int main(int argc, char *argv[]) {
    dates = malloc(CHILDREN_LIMIT * sizeof(struct test_date*)); // an array declared static of type struct test_date
    //... later
    struct test_date *td = &dates[children]; //children is a counter
    if (fork() == 0) { // in a child process
        td->pid = getpid();
        time(&(td->t));
        //now, if I print the date, I get a strange result. look bellow for get_time function.
        printf("%s\n", get_time(&td->t));
        //...
    }
    //...
    exit(0);
}

char *get_time(time_t *t) {

    struct tm *bt = malloc(sizeof(struct tm*));
    char *strt = malloc(DATE_SIZE * sizeof(char *));

    localtime_r(t, bt);
    strftime(strt, 100, "%Y-%m-%d %T", bt);
    return strt;
}
此代码的输出:

应该是:2013-07-16 09:21:28

但它是:2013-858861619-1609:21:28

更重要的是,如果我稍后调用相同的
printf
函数,在从子进程调用的某些函数中,我会得到更糟糕的结果。1974年的某个日期

谁能告诉我我的错在哪里?我想它应该是我传递
time\t
变量作为指针的地方,但我不明白为什么会有这种行为。有人能详细谈谈这个话题吗

struct tm *bt = malloc(sizeof(struct tm*));
char *strt = malloc(DATE_SIZE * sizeof(char *));
应该是:

struct tm *bt = malloc(sizeof(struct tm));
char *strt = malloc(DATE_SIZE * sizeof(char));
主菜单中

dates = malloc(CHILDREN_LIMIT * sizeof(struct test_date*)); 
应该是

dates = malloc(CHILDREN_LIMIT * sizeof(struct test_date)); 
struct tm *bt = malloc(sizeof(struct tm));
我认为您可能对malloc的用法有误解,请查阅手册,并使用此更安全的表单,有关详细信息,请参阅:

struct tm* bt = malloc(sizeof(*bt));

您正在分配的结构
tm
太小

应该是

dates = malloc(CHILDREN_LIMIT * sizeof(struct test_date)); 
struct tm *bt = malloc(sizeof(struct tm));

strftime
将一些数据写入malloc未分配的内存,这些数据可能是另一个已分配内存块的一部分,可能是strt的一部分。这可能会导致奇怪的值。这同样适用于
日期
数组的分配。

Malloc(CHILDREN\u LIMIT*sizeof(struct test\u date))从1970年1月1日开始。