0

Why does malloc always initialize with garbage values and calloc always intialize with 0? Any reason behind it?

Why can't we use realloc instead of malloc for dynamic memory allocation?

After reallocating memory dynamically, what are initial values of it?

Code:

int *ptr;
ptr = (int *) realloc(ptr,50);
printf("%d",*ptr);
alk
  • 69,737
  • 10
  • 105
  • 255
  • 3
    The code as presented will invoke *undefined behavior*. `ptr` has no determinate value prior to being passed to `realloc`, which requires one of (a) the value of `NULL`, or (b) the result of a `malloc`, `calloc`, `realloc`, or any derivative utilizing one of the above (ex: `strdup`, `getline`, etc.). That said, you *can* use `realloc` to replace `malloc` and `calloc`, if managed correctly. It is often an academic task given to up-and-coming C engineers to attempt to implement their own `malloc` and `calloc` using only `realloc` to do so. ex: `malloc(n)` == `realloc(NULL, n)` – WhozCraig Dec 15 '19 at 12:23
  • 1
    Also worth noting, `printf("%d",*ptr);` also invokes *undefined behavior*. There is no determinate value set at `*ptr` prior to encountering that statement (at least none in the posted code). Finally (seriously, done after this), [don't cast memory allocation library function results in C](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – WhozCraig Dec 15 '19 at 12:39

2 Answers2

3

malloc is made to just allocate memory of the specified size. calloc does the same (with different parameters), but is also designed to zero initialize the memory. It is just how they are designed.

You can use realloc for dynamic reallocation, but it is used to reallocate, which in your example it is not. realloc can only be used on memory already initialized with malloc, calloc, or realloc, or if the pointer is NULL then it is equivalent to malloc

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
3

Why does Malloc always initialize with Garbage values & Calloc always intialize with 0?

This behaviour is defined by the C standard.

In fact malloc() does not initialise the memory allocated at all. This mostly is for performance reasons. Do not read it, before having written to it yourself, to not provoke UB.

calloc() is specified to initialise the memory allocated to all 0s.

why can't we use realloc instead of malloc for dynamic memeory allocation.

You can. Just pass NULL as 1st parameter.

Your example adjusted:

int *ptr = NULL;
ptr = realloc(ptr, 50);
*ptr = 42;
printf("%d\n", *ptr);

prints:

42
alk
  • 69,737
  • 10
  • 105
  • 255