• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: When to use calloc or malloc in C

Resolved: When to use calloc or malloc in C

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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
VARIANT 2
The struct

Answer:

There are obvious and more subtile problems in your examples:
  • *void name; is a syntax error.

  • Neither struct _person* person = calloc(1, sizeof(person)); nor struct _person* person = malloc(sizeof(person)); will allocate the correct amount of memory because sizeof(person) will evaluate to the size of the pointer person in the definition, not the type person defined as a typedef for struct _person.


In both examples, you should the size of the data pointed to by the pointer:
Regarding whether to use calloc() or malloc(), it is much safer to always use calloc() for these reasons:
  • the size of the element and the number of elements are separate, thus avoiding silly mistakes in the overall size computation.
  • the memory is initialized to all bits zero, which is the zero value of all scalar types on modern systems. This may allow you to simplify the code by omitting explicit initialization of integers and will force initialization to 0 of all extra members added to the structure definition for which the allocation functions might be missing initializers.
  • for large arrays, calloc() is actually faster than malloc(size) + memset(s, 0, size), as is documented this answer: https://stackoverflow.com/a/18251590/4593267

If you have better answer, please add a comment about this, thank you!

Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Openlayers: Update clusters depending on filter (geometryFunction)

24/03/2023

Resolved: Getting ‘502 Bad Gateway’ while deploying Springboot app in EKS

24/03/2023

Resolved: Why is NGINX’s $request_uri empty?

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.