🖥️

Understanding Malloc in C Language

Sep 3, 2024

Notes on Malloc in C

Overview of Malloc

  • Malloc is a powerful function in the C standard library.
  • It allocates memory on the Heap as requested by the user.

Functionality of Malloc

  • Malloc takes a number of bytes as input.
  • It allocates the requested bytes on the Heap and returns a pointer to the allocated memory.

Type Consideration

  • Malloc does not know the type of the pointer returned.
  • In stricter languages like C++, you may need to cast the pointer appropriately.

Using Sizeof with Malloc

  • It is often beneficial to use sizeof with malloc to ensure correct memory allocation.
  • Example: To allocate memory for three integers:
    • Use the expression: malloc(sizeof(int) * 3)
    • This ensures the code is portable across different compilers.*

Error Handling

  • If more memory is requested than is available, malloc will return NULL.

Good Practices

  • Always free the allocated memory when done:
    • Use free(pointer) to release memory.
    • Assign the pointer to NULL after freeing it to avoid dangling pointers.

Additional Resources

  • Check out the playlist for more videos on related topics.