Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

c - malloc和calloc之间的区别?(Difference between malloc and calloc?)

What is the difference between doing:

(做的有什么区别:)

ptr = (char **) malloc (MAXELEMS * sizeof(char *));

or:

(要么:)

ptr = (char **) calloc (MAXELEMS, sizeof(char*));

When is it a good idea to use calloc over malloc or vice versa?

(什么时候使用calloc而不是malloc是一个好主意,反之亦然?)

  ask by user105033 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

calloc() zero-initializes the buffer, while malloc() leaves the memory uninitialized.

(calloc()将初始化缓冲区,而malloc()使内存未初始化。)

EDIT:

(编辑:)

Zeroing out the memory may take a little time, so you probably want to use malloc() if that performance is an issue.

(将内存清零可能需要一些时间,因此如果性能问题,您可能希望使用malloc() 。)

If initializing the memory is more important, use calloc() .

(如果初始化内存更重要,请使用calloc() 。)

For example, calloc() might save you a call to memset() .

(例如, calloc()可能会保存对memset()的调用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...