Malloc in C
×


Malloc in C

220

 malloc stands for "memory allocation." It's a function in C used for dynamic memory allocation.

 It allocates a block of memory of a specified size and returns a pointer to the first byte of the block.

 This memory is allocated from the heap section of memory.

Syntax of Malloc in C

void* malloc(size_t size);

 size: Size of the memory block to allocate in bytes.

 Return Type: void* (pointer to void) which can be cast to any data type.

Diagram:

Example:

// Program Malloc in C
#include<stdio.h>	
#include<stdlib.h>		

int main() {
    int *arr;
    int size = 5;

    // Allocate memory for 5 integers
    arr = (int*) malloc(size * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initialize array elements
    for (int i = 0; i < size; i++) {
        arr[i] = i + 1;
    }

    // Print array elements
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    // Free allocated memory
    free(arr);

    return 0;
}		
	

Output:

1 2 3 4 5

 Include necessary header files stdio.h and stdlib.h.

 Declare a pointer arr of type int.

 Use malloc to allocate memory for an integer array of size 5.

 Check if memory allocation was successful.

 Initialize array elements and print them.

 Free the allocated memory using free.

 In this example, malloc is used to dynamically allocate memory for an integer array of size 5.

 After using the allocated memory, it's important to free it using free to prevent memory leaks.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments