何时在C中使用Calloc或Malloc
什么更好/更高效 - calloc
或malloc
?
我想初始化结构,该结构是指同一结构的其他实例也是
变体1
person *new_person() {
struct _person *person = calloc(1, sizeof(person));
person->name = NULL;
person->child = NULL;
return person;
}
变体2
person *new_person() {
struct _person *person = malloc(sizeof(person));
person->name = NULL;
person->child = NULL;
return person;
}
结构
typedef struct _person {
*void name;
struct _person *child;
} person;
What's better/more efficient - calloc
or malloc
?
I want to initialise structs, that refer to other instances of the same struct also
VARIANT 1
person *new_person() {
struct _person *person = calloc(1, sizeof(person));
person->name = NULL;
person->child = NULL;
return person;
}
VARIANT 2
person *new_person() {
struct _person *person = malloc(sizeof(person));
person->name = NULL;
person->child = NULL;
return person;
}
The struct
typedef struct _person {
*void name;
struct _person *child;
} person;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
示例中有明显且更细微的问题:
*void name;
是语法错误。struct _person* person = calloc(1,sizeof(person));
norstruct _person* person = malloc(sizeof(person));
将分配正确的内存量是因为sizeof(person)
将评估指示中的指针在定义中,而不是定义为定义为一个的类型person
struct _person
。typedef
这是名称阴影的一个病理示例,因此,本地定义隐藏了外部范围中同一标识符的另一个定义。使用
-wshadow
让编译器检测并报告此类问题。在这两个示例中,您都应用指针指向的数据的大小:
关于是否使用
calloc()
malloc(),始终使用要安全得多calloc()
由于以下原因:0
以后添加到结构定义中,该定义可能会缺少初始化语句。calloc()
实际上比malloc(size)
+memset(s,0,size)
https://stackoverflow.com/a/18251590/4593267答案: :
malloc和calloc之间的差异?
There are obvious and more subtile problems in your examples:
*void name;
is a syntax error.Neither
struct _person* person = calloc(1, sizeof(person));
norstruct _person* person = malloc(sizeof(person));
will allocate the correct amount of memory becausesizeof(person)
will evaluate to the size of the pointerperson
in the definition, not the typeperson
defined as a typedef forstruct _person
.This is a pathological example of name shadowing, whereby a local definition hides another definition for the same identifier in an outer scope. Use
-Wshadow
to let the compiler detect and report this kind of problem.In both examples, you should the size of the data pointed to by the pointer:
Regarding whether to use
calloc()
ormalloc()
, it is much safer to always usecalloc()
for these reasons:0
of all extra members later added to the structure definition for which the allocation functions might be missing initializing statements.calloc()
is actually faster thanmalloc(size)
+memset(s, 0, size)
, as is documented this answer: https://stackoverflow.com/a/18251590/4593267A more general discussion of this topic is this other question:
Difference between malloc and calloc?