w3resource

C malloc() function

C malloc() function - A memory allocator

The malloc() function is used to reserve a block of storage of size bytes. Unlike the calloc() function, malloc() does not initialize all elements to 0.

Syntax malloc() function

void *malloc(size_t size)

Parameters malloc() function

Name Description Required /Optional
size Bytes to allocate. Required

Return value from malloc()

  • Returns a pointer to the reserved space.
  • NULL if not enough storage is available, or if size was specified as zero.

Example: malloc() function

The following example shows the usage of malloc() function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(10);
   strcpy(str, "w3resource.com");
   printf("String = %s,  Address = %u\n", str, str);

   /* Deallocate allocated memory */
   free(str);
   return(0);
}

Output:

String = w3resource.com,  Address = 1905632

C Programming Code Editor:

Previous C Programming: C free()
Next C Programming: C realloc()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdlib/c-malloc.php