difference between malloc and calloc

I know two differences.

1) they differ in the no. of arguments they take
2) malloc returns uninitialized memory whereas calloc initializes it to zero.

I have 3 questions to ask.

1)Are there any other differences?

2) C compilers can re-implement malloc so that they also initialize the memory allocated, thus obliterating the need for calloc. Why C compilers or C STANDARD committees (ISO/ANSI) have not done this?

3)Whatever calloc does can be done in malloc itself. Is there ANY ONE SITUATION which demands only the use of calloc and NOT malloc?


Comments

  • [b][red]This message was edited by stober at 2004-10-31 8:53:41[/red][/b][hr]
    : I know two differences.
    :
    : 1) they differ in the no. of arguments they take
    : 2) malloc returns uninitialized memory whereas calloc initializes it to zero.
    :
    : I have 3 questions to ask.
    :
    : 1)Are there any other differences?
    :
    : 2) C compilers can re-implement malloc so that they also initialize the memory allocated, thus obliterating the need for calloc.

    [red]No they can't. If they did that then they woould not be ANSI C compliant.[/red]

    Why C compilers or C STANDARD committees (ISO/ANSI) have not done this?
    [red]I don't know, but my guess is that do that would be a waste of CPU time (see below)[/red]
    :
    : 3)Whatever calloc does can be done in malloc itself. [red]Wrong[/red]

    Is there ANY ONE SITUATION which demands only the use of calloc and NOT malloc?[red]No. calloc() calls malloc(). If you want to initialize the memory yourself with 0s then call memset().[/red]
    :
    :
    :


    [blue]calloc() calls malloc() to allocate the memory then initializes it to all 0s. Otherwise, there is no difference between the two functions. It is never absolutely necessary to use calloc() because you can do that yourself if you want to. Usually calloc() is NOT called when you want to initialize the memory to something else. For example, if you want to allocate memory for text that is read from a file there would be no point to using calloc() to initialize it to 0 when you turn right around and read a file that fills the memory with something else.

    Here is how calloc really works[/blue]
    [code]
    void* MyCalloc(size_t nItems, size_t ItemSize)
    {
    // total memory size needed
    size_t total_size = nItems * ItemSize;
    // allocate the memory
    char* ptr = (char*)malloc(total_size);
    if(ptr != NULL)
    // initilize memory with 0s
    memset(ptr,0,total_size);
    return ptr;
    }
    [/code]






Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion