C - calloc() v. malloc()

Possible Duplicate:
c difference between malloc and calloc

Please explain the significance of this statement,

Another difference between the malloc() and calloc() functions is that the memory allocated by malloc( ) function contains garbage values, while memory allocated by calloc( ) function contains all zeros.

Source ('C' Programming, Salim Y. Amdani)


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

From http://wiki.answers.com/Q/Is_it_better_to_use_malloc_or_calloc_to_allocate_memory

malloc() is faster, since calloc() initializes the allocated memory to contain all zeros. Since you typically would want to use and initialize the memory yourself, this additional benefit of calloc() may not be necessary.

calloc is initializing the memory before you use it, but malloc does not.

Refer to this link:

The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0.

With malloc, if you want to guarantee the same effect you'd have to call something like memset to reset the memory, e.g.

char* buffer = (char*)malloc(100);

calloc saves you that extra step. The significance of initializing memory is that you are getting a variable to a known state rather than an unknown one. So if you are checking a variable, say an array element, for an expected value, then by having pre-initialized the variable ahead of time, you can be sure that the value you are checking isn't garbage. In other words, you can distinguish between garbage and legitimate values.

For example, if you just leave garbage in the variable and you are checking for some value, say 42, then you have no way of knowing if the value was really set to 42 by your program, or if that's just some garbage leftover because you didn't initialize it.

It just means that if you allocate memory, with calloc(), whatever you allocate is 0. i.e. if you allocated space for an array of integers, they'd all be set to 0, whereas with malloc(), the memory there isn't initialized in any way.

You could use calloc in situations where you are just going to do a memset of 0 to the memory anyway.

calloc(...) is basically malloc + memset:

ptr = (struct fubar*) malloc(sizeof(struct fubar));
memset(ptr, 0, sizeof (struct fubar));

When you use malloc to allocate some memory, it's previous contents are not cleared (ie not initialized). You might get random values that were set when machine booted up or you might see some of the memory that belonged to previously running programs but was left uncleared after allocation and program exit.

calloc itself is slower than malloc because you have to spend some time to clear the contents of allocated memory. So if you just need to allocate some memory and then copy some stuff there, you are free to use malloc.

Category:c# Views:1 Time:2010-08-10
Tags: c# malloc calloc

Related post

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

    I am following this tutorial (http://theocacao.com/document.page/234). 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

  • Does realloc and calloc call malloc? 2011-07-14

    This is probably an easy question but I couldn't find an answer. Is malloc internally called within realloc and within calloc? Since I am somehow counting the malloc calls, it is interesting for me. Thanks --------------Solutions------------- You sho

  • When should i use calloc over malloc 2011-11-12

    This is from Beej's guide to C "The drawback to using calloc() is that it takes time to clear memory, and in most cases, you don't need it clear since you'll just be writing over it anyway. But if you ever find yourself malloc()ing a block and then s

  • 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

  • Why malloc+memset is slower than calloc? 2010-04-22

    It's known that calloc is different than malloc in that it initializes the memory allocated. With calloc, the memory is set to zero. With malloc, the memory is not cleared. So in everyday work, I regard calloc as malloc+memset. Incidentally, for fun,

  • 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

  • I'm very confused about malloc() and calloc() on C 2010-11-21

    I've always programmed in Java, which is probably why I'm so confused about this: In Java I declare a pointer: int[] array and initialize it or assign it some memory: int[] array = {0,1,0} int[] array = new int[3] Now, in C, it's all so confusing. At

  • preferring malloc over calloc 2010-11-22

    Possible Duplicate: c difference between malloc and calloc Is there any situation where you would prefer malloc over calloc. i know both malloc and calloc allocate memory dynamically and that calloc also initializes all bits in alloted memory to zero

  • Understanding the purpose of malloc and calloc 2011-12-11

    I'm trying to get my head around C. Reading through K&R, I am flicking back and forth trying to find where it states the situations I should obtain blocks of memory dynamically. For example, I want to have an int pointer. int *pointer; But then K

  • In what cases do I use malloc vs new? 2008-10-08

    I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (e.g. Calling free() on so

  • 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

  • How do malloc() and free() work? 2009-07-13

    I want to know how malloc and free work. int main() { unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char)); memset(p,0,4); strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes** cout << p; free(p); // Obvious Crash, but I

  • calloc - Usefulness of zeroing out memory 2010-02-13

    What is the advantage of zeroing out memory (i.e. calloc() over malloc())? Won't you change the value to something else anyways? --------------Solutions------------- There are two camps: one says that initializing variables when they are declared hel

  • calling calloc - memory leak valgrind 2010-05-27

    The following code is an example from the NCURSES menu library. I'm not sure what could be wrong with the code, but valgrind reports some problems. Any ideas... ==4803== 1,049 (72 direct, 977 indirect) bytes in 1 blocks are definitely lost in loss re

  • how can i know if calloc fails to initialize 2012-02-15

    I have read that calloc (malloc+init) will sometimes fail to init array with zero bytes (but will still return pointer to a malloc'ed array). but in documentation it does not specify that it will return NULL, is there a way to be sure that array was

  • Attempted to read or write protected memory when calling native C DLL 2009-02-24

    I have a native C dll that exports one function besides DllEntryPoint, FuncX. I'm trying to find out how FuncX communicates with it's caller, because it has a void return type and no parameters. When I call it from a C# harness, I get an AccessViolat

  • Is this a good substr for C? 2009-05-17

    See also C Tokenizer Here is a quick substr() for C that I wrote (yes, the variable initializations needs to be moved to start of the function etc, but you get the idea) I have seen many "smart" implementations of substr() that are simple one liner c

  • Windows utility for consuming CPU 2009-10-29

    I'm looking for a windows utility to consume CPU at a specified percentage so that I can test my app under conditions of restricted processor resources. I googled around and saw a reference to CPUGRAB.exe, but can't find a download location. --------

  • Modifying a structure array through a pointer passed to a function 2009-11-29

    I am trying to pass a structure array pointer and a pointer to a structure array pointer into a function and then have it modified rather than using a return. This example code is indeed pointless, its just a learning example for me. Basically I want

Copyright (C) dskims.com, All Rights Reserved.

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