Home  >  Article  >  Backend Development  >  In C language, the malloc function is used to dynamically allocate memory.

In C language, the malloc function is used to dynamically allocate memory.

WBOY
WBOYforward
2023-09-18 11:41:141157browse

In C language, the malloc function is used to dynamically allocate memory.

The malloc() function represents memory allocation and dynamically allocates a piece of memory.

It reserves a memory space of the specified size and returns a null pointer to the memory location.

malloc() function carries garbage values. The returned pointer is of type void.

The syntax of the malloc() function is as follows -

ptr = (castType*) malloc(size);

Example

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

Live demonstration

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
   char *MemoryAlloc;
   /* memory allocated dynamically */
   MemoryAlloc = malloc( 15 * sizeof(char) );
   if(MemoryAlloc== NULL ){
      printf("Couldn&#39;t able to allocate requested memory</p><p>");
   }else{
      strcpy( MemoryAlloc,"TutorialsPoint");
   }
   printf("Dynamically allocated memory content : %s</p><p>", MemoryAlloc);
   free(MemoryAlloc);
}

Output

When the above program is executed, the following results will be produced -

Dynamically allocated memory content: TutorialsPoint

The above is the detailed content of In C language, the malloc function is used to dynamically allocate memory.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete