在 Pthreads 中使用 malloc
Use of malloc in Pthreads
这是来自 Pthreads 的实际 C 代码:
ThreadParms *parms = NULL;
if ((parms = (ThreadParms *) malloc (sizeof (*parms))) == NULL)
{
goto FAIL0;
}
parms->tid = thread;
parms->start = start;
parms->arg = arg;
为什么他们选择 malloc *parms 而不是 ThreadParms?看起来它只分配了一个指针(这将是一个错误),但它显然分配了整个结构的大小。这是正确的吗?
*parms
是 ThreadParms
类型所以大小合适
有时人们认为这样做比旧的 sizeof(ThreadParms)
更好,因此如果 parms
的类型更改大小如下(赋值和 sizeof
语句在同一行)
(但这并不完美,并且在使用同一行分配其他类型时不能防止 copy/paste 错误,但通常更好)
这是 C 中的一个常见技巧 - 使用解引用指针表达式代替实际类型。
理由如下:如果你有
some_type *some_var = malloc(sizeof(*some_var));
然后将 some_type
更改为 some_other_type
,代码将继续正常工作,只需进行一处更改。
但是,如果您从
some_type *some_var = malloc(sizeof(some_type));
那么你必须在两个地方更改some_type
:
some_other_type *some_var = malloc(sizeof(some_other_type));
否则您的代码会出错。
It looks like it is allocating only a pointer (which would be an error)
星号使得 sizeof
计算出整个 struct
的大小,所以代码是正确的。
Why did they choose to malloc *parms instead of ThreadParms.
如果将来 parms
的类型发生变化,那么使用 so 是一种常见的做法,那么维护起来就更容易了。但是使用 ThreadParms
也同样有效。
It looks like it is allocating only a pointer (which would be an
error), but it apparently allocating the size of the whole structure.
Is this correct?
没有。它实际上等同于使用 sizeof(ThreadParms)
,因为 sizeof 运算符只需要类型信息而不计算其操作数(C99 Variable Length Arrays 除外)。 *parms
的类型是 ThreadParms
,这就是 sizeof
需要知道的全部内容。
旁注:在 C 中不需要强制转换为 ThreadParms *
,因为 void *
可以分配给任何其他数据指针。
这是来自 Pthreads 的实际 C 代码:
ThreadParms *parms = NULL;
if ((parms = (ThreadParms *) malloc (sizeof (*parms))) == NULL)
{
goto FAIL0;
}
parms->tid = thread;
parms->start = start;
parms->arg = arg;
为什么他们选择 malloc *parms 而不是 ThreadParms?看起来它只分配了一个指针(这将是一个错误),但它显然分配了整个结构的大小。这是正确的吗?
*parms
是 ThreadParms
类型所以大小合适
有时人们认为这样做比旧的 sizeof(ThreadParms)
更好,因此如果 parms
的类型更改大小如下(赋值和 sizeof
语句在同一行)
(但这并不完美,并且在使用同一行分配其他类型时不能防止 copy/paste 错误,但通常更好)
这是 C 中的一个常见技巧 - 使用解引用指针表达式代替实际类型。
理由如下:如果你有
some_type *some_var = malloc(sizeof(*some_var));
然后将 some_type
更改为 some_other_type
,代码将继续正常工作,只需进行一处更改。
但是,如果您从
some_type *some_var = malloc(sizeof(some_type));
那么你必须在两个地方更改some_type
:
some_other_type *some_var = malloc(sizeof(some_other_type));
否则您的代码会出错。
It looks like it is allocating only a pointer (which would be an error)
星号使得 sizeof
计算出整个 struct
的大小,所以代码是正确的。
Why did they choose to malloc *parms instead of ThreadParms.
如果将来 parms
的类型发生变化,那么使用 so 是一种常见的做法,那么维护起来就更容易了。但是使用 ThreadParms
也同样有效。
It looks like it is allocating only a pointer (which would be an error), but it apparently allocating the size of the whole structure. Is this correct?
没有。它实际上等同于使用 sizeof(ThreadParms)
,因为 sizeof 运算符只需要类型信息而不计算其操作数(C99 Variable Length Arrays 除外)。 *parms
的类型是 ThreadParms
,这就是 sizeof
需要知道的全部内容。
旁注:在 C 中不需要强制转换为 ThreadParms *
,因为 void *
可以分配给任何其他数据指针。