Home > Backend Development > C++ > body text

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

WBOY
Release: 2023-09-18 11:41:14
forward
1159 people have browsed it

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);
Copy after login

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);
}
Copy after login

Output

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

Dynamically allocated memory content: TutorialsPoint
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template