A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm below:

C malloc Function

C library - malloc() function

The C stdlib library malloc() function is used for dynamic memory allocation. It allocates or reserves a block of memory of specified number of bytes and returns a pointer to the first byte of the allocated space.

The function malloc() is used when the required size of memory is not known at compile time and must be determined at runtime.

Syntax

Following is the C library syntax of the malloc() function −

void *malloc(size_t size)
Parameters

This function accepts a single parameter −

Return Value

following is the returns value −

Example 1

Let's create a basic c program to demonstrate the use of malloc() function.

#include <stdio.h>
#include <stdlib.h>
int main() {
   int *pointer = (int *)calloc(0, 0);
   if (pointer == NULL) {
      printf("Null pointer \n");
   } 
   else {
      printf("Address = %p", (void *)pointer);
   }
   free(pointer);
   return 0;
}
Output

Following is the output −

Address = 0x55c6799232a0
Example 2

Following is the another of malloc(). Here it is used to allocate memory for an array of 5 integers.

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

int main() {
   int *ptr;
   int n = 5;
   
   // Dynamically allocate memory using malloc()
   ptr = (int*)malloc(n * sizeof(int));
   
   // Check if the memory has been successfully allocated
   if (ptr == NULL) {
      printf("Memory not allocated.\n");
      exit(0);
   } else {
      // Memory has been successfully allocated
      printf("Memory successfully allocated using malloc.\n");
   
      // Free the memory
      free(ptr);
      printf("Malloc memory successfully freed.\n");
   }
   return 0;
}
Output

Following is the output −

Memory successfully allocated using malloc.
Malloc memory successfully freed.
Example 3

The below c program dynamically stores the array element in the pointer and calculate the sum of array's element.

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

int main() {
   int n = 5, i, *ptr, sum = 0;
   int arr[] = {10, 20, 30, 40, 50};
   
   ptr = (int*) malloc(n * sizeof(int));
   
   // if memory cannot be allocated
   if(ptr == NULL) {
      printf("Error! memory not allocated.");
      exit(0);
   }
   
   // Copy values from arr to dynamically allocated memory
   for(i = 0; i < n; ++i) {
      *(ptr + i) = arr[i];
      sum += *(ptr + i);
   }   
   printf("Sum = %d", sum);
   
   // free the allocated memory
   free(ptr);
   return 0;
}
Output

Following is the output −

Sum = 150

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4