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