Latest web development tutorials

C library functions - malloc ()

C standard library - <stdlib.h> C standard library - <stdlib.h>

description

C library functionsvoid * malloc (size_t size) allocate the required memory space and returns a pointer to it.

statement

Here is () statement malloc function.

void *malloc(size_t size)

parameter

  • size - the size of the memory block, in bytes.

return value

This function returns a pointer to the allocated memory size. If the request fails, it returns NULL.

Examples

The following example demonstrates the malloc () function is used.

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

int main()
{
   char *str;

   /* 最初的内存分配 */
   str = (char *) malloc(15);
   strcpy(str, "w3cschool");
   printf("String = %s,  Address = %u\n", str, str);

   /* 重新分配内存 */
   str = (char *) realloc(str, 25);
   strcat(str, ".cc");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);
   
   return(0);
}

Let's compile and run the above program, which will result in the following:

String = w3cschool, Address = 355090448
String = w3cschool.cc, Address = 355090448

C standard library - <stdlib.h> C standard library - <stdlib.h>