-1

The following is one minimal example to reproduce the problem. To me, the code looks quite innocent. I suspect there's some magic behind struct timespc; however, I can't find anything that could explain why it crashes.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>

typedef struct _task
{
    int id;
    int deadline;
    struct timespec processed_at;
    int process_time;
} task;

int main(int argc, char *argv[])
{
    task *t = malloc(sizeof t);
    t->process_time = 3;
    free(t);
    return 0;
}
M.M
  • 138,810
  • 21
  • 208
  • 365
Albert Netymk
  • 1,102
  • 8
  • 24
  • 4
    Because you're only mallocing enough room for a pointer. – Oliver Charlesworth Sep 12 '14 at 20:49
  • 1
    Don't edit the answer into your question, it makes it confusing for pepole reading the question for the first time. Instead, accept one of the posted answers. If no good answers are posted but you have solved the problem, you can write your own answer and accept it. – M.M Sep 13 '14 at 12:56

1 Answers1

2

All the exiting answers and comments point out the critical part where the mistake is. However, some usage of sizeof is incorrect so I am answering this question.

I looked at this SO carelessly, and assumed the OP provides the correct syntax. Since he/she is talking about why style to use, I expect both are correct.

As for whether it's used with () or without (), according to cppreference, () is needed for type, but not for unary-expression. Therefore, sizeof task is incorrect (I get error on clang and gcc); instead, it should be sizeof(task) or sizeof *t.

task *t = malloc(sizeof *t); // right
task *t = malloc(sizeof(task)); // right
task *t = malloc(sizeof task); // wrong both on gcc and clang
task *t = malloc(sizeof t); // syntactically right, but it's not what you want
Community
  • 1
  • 1
Albert Netymk
  • 1,102
  • 8
  • 24
  • In my opinion, the first form is also the most preferable as it avoids duplication and thus survives changing the type name specified at the beginning of the line, which is even more notable in more complex scenarios like array allocation/reallocation. As a side effects, it avoids the need for parentheses. – Pavel Šimerda Sep 14 '14 at 18:36
  • @OliverCharlesworth surprised you didn't complain that number 2 is wrong and that 3 is right... – UpAndAdam Oct 01 '14 at 14:41