1

Here is what I have:

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

The output for this code:

eg. It should be: 2013-07-16 09:21:28

But it is: 2013-858861619-16 09:21:28

Even more, if I call the same printf function later, in some functions called from child process, I get an even worse result. A date somewhere to 1974.

Can anybody tell me where is my mistake? I guess it should be where I pass the time_t variable as pointer, but I can't understand why this behavior. Can anybody detail on this topic?

artaxerxe
  • 6,281
  • 21
  • 68
  • 106

2 Answers2

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

should be:

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

In the main:

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

should be

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

I think you may have a mis-understanding of the usage of malloc, check out a manual, and use this safer form, see here for detail:

struct tm* bt = malloc(sizeof(*bt));
Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

The struct tm you are allocating is too small.

It should be

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

strftime write some data into memory that was no allocated by malloc which could be part of another allocated chunk of memory, maybe that of strt. This could cause the strange values. The same also applies to allocation of dates array.

bkausbk
  • 2,740
  • 1
  • 36
  • 52