C中日期的奇怪行为

时间:2013-07-16 06:50:30

标签: 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 *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-16 09:21:28

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

有谁能告诉我我的错误在哪里?我想它应该是我将time_t变量作为指针传递的地方,但我无法理解为什么会出现这种情况。有人可以详细介绍这个主题吗?

2 个答案:

答案 0 :(得分:2)

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));

main

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

应该是

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

我认为您可能对malloc的使用情况有误解,查看手册并使用此更安全的表单,请参阅here了解详细信息:

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

答案 1 :(得分:1)

您分配的结构tm太小了。

应该是

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

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