-
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
-
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 */