-1

以下是重现该问题的一个最小示例。对我来说,代码看起来很无辜。我怀疑背后有一些魔力struct timespc;但是,我找不到任何可以解释它为什么崩溃的东西。

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

1 回答 1

2

所有现有的答案和评论都指出了错误所在的关键部分。但是,sizeof 的某些用法不正确,所以我正在回答这个问题。

我漫不经心地看着这个,并假设 OP 提供了正确的语法。由于他/她在谈论为什么要使用样式,我希望两者都是正确的。

至于是带()还是不带(),根据cppreference,type需要(),unary-expression不需要。因此,sizeof task不正确(我在 clang 和 gcc 上遇到错误);相反,它应该是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
于 2014-09-14T18:30:36.240 回答