Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

malloc

  • malloc is a standard library function in C that provisions memory on the heap and returns a pointer to the beginning of the allocated memory block.
  • This new memory is uninitialized, meaning it contains whatever data was previously stored in those memory pages.
  • In contrast, calloc allocates memory and zeros it out.
  • The programmer must remember to eventually free the allocated memory using free() to avoid memory leaks. free() does not change the value stored in the memory, and it doesn’t even change the address stored in the pointer, it simply tells the operating system that this memory can be reused. That’s it.

Function signature:

void* malloc(size_t size);

Example:

// Allocates memory for an array of 4 integers
int *ptr = malloc(4 * sizeof(int));
if (ptr == NULL) {
  // Handle memory allocation failure
  printf("Memory allocation failed\n");
  exit(1);
}
// use the memory here
// ...
free(ptr);