4

Do you prefer calloc or malloc?

Comments
  • 1
    Malloc for quickly initialized memory, calloc for long-lived arena-style memory that you don't want garbage floating around in until it's allocated. Seems like they aren't really comparable to me but I'm not very experienced using it directly
  • 0
    Both 🤷
  • 1
    Both, depends on how the memory will be used.
    That said I like new and placement new a lot more.
  • 1
    I use calloc if either:

    - The next like would be a bzero / memset to clear the memory.
    - I'm doing something like malloc(sizeof(int) * 4).
  • 3
    Always use calloc unless you are doing repeated alloc/free and it hampers performance - and even then you should better redesign the application.

    Malloc initialises a buffer to 0 when you allocate that memory for the first time, but can return your own garbage from earlier runs upon subsequent allocations. That alone introduces stateful behaviour that makes testing more difficult.

    But the killer is the danger of multiplication overflow in the allocation because malloc is usually called as product of element size and count while these are two separate parameters in calloc.
  • 0
    I prefer C#
  • 0
Your Job Suck?
Get a Better Job
Add Comment