Search code examples
cundefined-behavior

Is it UB to read bytes from malloc() without initializing them first?


In C, if I malloc(N) a buffer, for what operations is that buffer valid? E.g.

  • a buffer starting at malloc(N) is invalid for reads until initialized
  • a buffer starting at malloc(N) is valid for writes of at least size N (but maybe greater).

Solution

  • When you use malloc(), each byte is uninitialized until you initialize it. So reading from it is like reading from any other uninitialized variable.

    You can instead use calloc(), which automatically initializes all bytes to 0.

    For writing, you can write at most N bytes, not greater.