2

My program is a task list manager... it takes the name, priority, and date of a task using fgets/stdin and puts it in a struct. This is the relevant snippet of my program:

task *makeTask(char *name, char *date, char *priority)
{

        task *the_task = malloc(sizeof(task));

        int i;

        the_task->task_name = (char*)malloc(sizeof(char) * (strlen(name)));

         for (i=0;name[i] != '\n'; i++) {
                if (name[i] != '\0')
                the_task->task_name[i] = name[i];
        }

        the_task->task_name[i] = '\0';

        //already allocated for in struct
        for (i=0;date[i] != '\n'; i++) {
                if (date[i] != '\0')
                the_task->date_entered[i] = date[i];
        }

        the_task->date_entered[i] = '\0';


        the_task->priority = atoi(priority);
        return the_task; // FILE THIS IN
}

Here's the expected output:

0: Feed the cats, priority: 5.  Entered 01/01/1111

And here's the actual output:

0: edsats, priority: 5.  Entered 01/01/1111

I've been scratching my head for the past hour trying to fix this problem... what's going on with my code?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user1787531
  • 789
  • 4
  • 10
  • 22

2 Answers2

1

I would suggest a couple of things:

  • You need an extra byte to store the task name, to hold the null terminator
  • use strdup to allocate memory for a string and copy it into it (for the task name)
  • use strcpy to copy the date into its preallocated string

I'm also uncertain if you're showing us the code that is actually causing the problem, but try fixing the task name memory block to see if that helps.

lxop
  • 7,596
  • 3
  • 27
  • 42
1
  1. You don't allocate space for the_task->date_entered.

  2. You need to add strlen(name) + 1 bytes to account for the null terminator.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578