Thread: calloc

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    2

    calloc

    Hi,
    calloc is used like calloc(no_of_elements,size_of_element).
    During memory allocation deallocation. you will create a hole in heap. which you can use for memory allocation.

    Now my question is.

    is it possible to use such hole for memory allocation which are not continuous in memory. suppose you have 10 holes of 1 byte no continous. now you need 10 bytes. if i will use malloc it will fail but when i will use calloc, will it allocate.

    second thing, i am assigning the address of hole to pointer which will monitor 10 bytes. but how can i access rest 9 bytes.


    i am completely confused, where should i use calloc and malloc.

    Thanks

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Both malloc() and calloc() allocate a contiguous block of memory. The only difference is that calloc() sets the memory allocated to zero. So, if malloc(no_of_elements*size_of_element) would fail, so would calloc(no_of_elements, size_of_element).

    You should NEVER assign the address of a "hole" (your word, not mine) to any pointer: that would give you a dangling pointer (a pointer to memory that may no longer be available for use by the program). Any attempt to access such memory (read its value or write to it) gives undefined behaviour.

    However, if the pointer is valid (i.e. not dangling) pointer or array syntax can be used. For example;
    Code:
       char *p = some_valid_block_of_ten_chars();
       p [0] = 'A';     /*  valid */
       p[9] = 'Z';      /*   valid */
       p[10] = 'Q';    /*   invalid:  cannot access 11th char if the buffer is only 10 char */
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. re-calloc???
    By audinue in forum C Programming
    Replies: 6
    Last Post: 07-20-2008, 05:06 PM
  2. calloc
    By goran00 in forum C Programming
    Replies: 27
    Last Post: 04-07-2008, 12:50 PM
  3. Using calloc
    By giancu in forum C Programming
    Replies: 10
    Last Post: 11-07-2007, 01:32 PM
  4. Why use calloc()?
    By dwks in forum C Programming
    Replies: 8
    Last Post: 07-20-2005, 08:22 AM
  5. calloc()
    By goresus in forum C Programming
    Replies: 3
    Last Post: 01-20-2005, 09:50 AM