Two arguments to calloc

Why does calloc take two arguments instead of one like malloc?

Specifically, since there is no difference between (or is there?) between the following expressions:

calloc (a, b); calloc (b, a); calloc (a * b, 1); calloc (1, a * b);

why not just accept the total number of bytes to allocate? What is the rationale behind this interface? And why does this not apply to malloc?

-------------Problems Reply------------

I heard two [mutually exclusive] explanations for why it has two arguments:

  1. calloc takes the responsibility for checking for overflow on multiplication. If the total size of the requested block is too large (like overflows size_t), calloc returns null pointer to indicate failure. With malloc you have to watch for overflow yourself, which many people simply forget to do. (Although the history of standard library knows examples of calloc implementations that ignored overflow, and thus worked incorrectly).
  2. calloc actually allows one to allocate bigger blocks of memory than the range of type size_t, i.e. calloc might be capable of performing the proper non-overflowing large multiplication of its arguments and allocate the block of the resultant size. For this reason, since calloc uses two arguments of type size_t, it can allocate bigger blocks than malloc will ever be able to (since malloc takes only one argument of type size_t).

I always believed that the first explanation is the right one. However, after reading some posts here on SO I have my doubts.

I believe that malloc is guaranteed to return an area of memory which is aligned according to the coarsest requirement that would be compatible with the size indicated by the second argument. For example, if the system requires alignment of 2 and 4-byte integers, and the second argument is 10, the returned pointer must be aligned on a two-byte boundary; if the second argument were 12, the pointer would be aligned on a four-byte boundary. I suspect that in practice many systems will align all returned pointers to the largest possibly-required boundary, regardless of size, but I don't think it's required except for calloc.

The only notable difference is that calloc is required to initialize the allocated space to zeroes while there is no such guarantee with malloc. Otherwise, I guess there are two different functions just for historical reasons.

Everything is just bytes is a relatively new (ie c/Unix era) invention - on a lot of other architecture things were fixed sized records.

calloc(x,y) is a equivalent to malloc(x*y)

But calloc doing additional (setting values to 0 with) memset(block, 0, x*y)

This function is only for pretty way pass the size of element and number of elements, when in malloc you must multiply this values to get needed number of bytes, this function check integer overflow too in multiplication.

For example if you want allocate memory for 12 integers and you want do something with this integers and you must have setted her values to 0, use calloc(12, sizeof(int))

But if you want allocate some memory block (256 bytes) to copy in future to it some string then memset is a not usable for you, then better use is malloc(sizeof(char) * 256) or for example malloc(sizeof(wchar_t) * 256)

void *
calloc (size_t nmemb, size_t lsize)
void *ptr;
struct __meminfo *info;
size_t size = lsize * nmemb;

/* if size overflow occurs, then set errno to ENOMEM and return NULL */
if (nmemb && lsize != (size / nmemb))
set_errno (ENOMEM);
return NULL;

/* allocate memory */
ptr = malloc (size);

/* get pointer to info part of chunk */
info = __mem2info (ptr);

/* fill memory with zeros and set __MEM_CALLOC flag */
memset (ptr, 0, info->size);
info->flags |= __MEM_CALLOC;

return ptr; /* happy end */

Category:c# Views:0 Time:2010-11-03
Tags: c# calloc

Related post

  • calloc v/s malloc and time efficiency 2010-04-09

    I've read with interest the post C difference between malloc and calloc. I'm using malloc in my code and would like to know what difference I'll have using calloc instead. My present (pseudo)code with malloc: Scenario 1 int main() { allocate large ar

  • Array index limit in C 2009-09-03

    On Linux, with 16 GB of RAM, why would the following segfault: #include <stdlib.h> #define N 44000 int main(void) { long width = N*2 - 1; int * c = (int *) calloc(width*N, sizeof(int)); c[N/2] = 1; return 0; } According to GDB the problem is fr

  • having memcpy problem 2010-07-06

    char *a=NULL; char *s=NULL; a=(char *)calloc(1,(sizeof(char))); s=(char *)calloc(1,(sizeof(char))); a="DATA"; memcpy(s,a,(strlen(a))); printf("%s",s); Can you plz tell me why its printing DATA½½½½½½½½■ε■????How to print only DATA?? Thanks -----------

  • Is calloc(4, 6) the same as calloc(6, 4)? 2009-02-01

    I'm a beginner C programmer, and I assumed that this would be the case, but would like some affirmation if possible. If they are the same, why not just take one argument instead? --------------Solutions------------- It is the same. The reason is beca

  • Difference between malloc and calloc? 2009-10-08

    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? --------------Solutions------------- callo

  • Struggling to use calloc and realloc to initialize arrays in C 2010-02-06

    I'm struggling to use calloc and realloc for my array initializations. I'm trying to write a program which calculates a final sum from the command line arguments using fork() with a companion program. If I receive a odd set of integers from the comma

  • C tutorial question relating to calloc vs malloc 2010-02-06

    I am following this tutorial ( I am confused about this paragraph, mainly the lines relating to calloc: We can also use a variation of the malloc function, called calloc. The calloc function takes two arguments

  • C - Malloc or calloc-and how? 2010-04-30

    i have a text file where the first number defines the size of the arrays. I know that calloc or malloc can reserve memory, but how? this code: typedef struct alpha { int* size; char name; int tot; char line[60]; } ALPHA; fgets(line, 60, fp); tot = at

  • C function to escape string for shell command argument? 2010-09-08

    What function should I use to escape strings for shell command argument in C? I have a string: This is a string with () characters This will be error: echo This is a string with () characters These are OK: echo "This is a string with () characters" e

  • Automatic passing of argument by reference in C 2010-09-24

    I'm writing a Unicode library for C as a personal exercise. Without the actual code, I have this: typedef struct string { unsigned long length; unsigned *data; } string; // really simple stuff string *upush(string *s, unsigned c) { ... } // UTF-8 con

  • Passing arguments generically in C 2011-01-11

    This is related to a homework assignment, but it seems like a common problem, hence the question. I have two structs typedef struct Vector { Element **elements; int top; int max_size; } Vector; typedef void Element; a vector is comprised of elements,

  • Is there a way to pass the entire argument list to another method in Objective C? 2011-01-27

    I'd like to be able to pass all the arguments received in my method to a different method, as generically as possible. Ideally, this would be done by passing a dictionary or some system variable (similar to _cmd). In other words, I'm looking for some

  • Lua C API: Handling and storing additional arguments 2011-03-27

    CreateEntity is a C function I bound to Lua in my project. It takes an entity class name string as first argument, and any number of additional arguments which should get passed to the constructor of the chosen entity. For example, if CreateEntity wa

  • Returning integer array from function with no arguments 2011-05-03

    Possible Duplicate: Returning local data from functions in C and C++ via pointer I need to create a function with no arguments that returns an array I get the error: "warning: function returns address of local variable" my code has been simplified fo

  • building a string out of a variable amount of arguments 2011-06-17

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> int main(int argc, char * argv[]) { char *arr[] = { "ab", "cd", "ef" }; char **ptr, **p, *str; int num = 3; int size = 0; ptr = calloc(num, 4); p =

  • How can i pass following arguments in main through argc and argv? 2011-07-15

    static void build_preprocess_command(int e_flag) { ivlpp_main(argc, argv); snprintf(tmp, sizeof tmp, "%s%civlpp %s%s -F\"%s\" -f\"%s\" -p\"%s\" ", pbase, sep, verbose_flag?" -v":"", e_flag?"":" -L", defines_path, source_path, compiled_defines_path);

  • C : Working with structures and pointers , error : invalid type argument of unary '*' 2011-10-08

    I'm working on a c program and here is the structure I am using struct EngineParts{ int serial_number; unsigned int year_of_manufacture; unsigned int quantity; char *material; }*Eparts; And I am getting the following error `Automobile.c:79:5: error:

  • Where does the OS store the command line arguments? 2011-10-11

    I am working on Linux. In which section of memory are the command line arguments stored (stack or heap)? I tried to execute free(argv) and I got a segmentation fault. Why is that? --------------Solutions------------- I tried to execute free(argv) and

  • Dynamic memory allocation questions with realloc and calloc 2011-11-18

    See the following function: int go(void) { int *p, *q; p = calloc(10,sizeof(int)); q = realloc(p, 20 * sizeof(int)); <<X>> } Assuming that both memory allocation function calls are successful, which of the following statements are true at

Copyright (C), All Rights Reserved.

processed in 0.127 (s). 11 q(s)