MAKAUT BTech CSE 2017 – My Blog https://beforebell.com/blog Learning through sharing Sat, 17 Sep 2022 19:44:16 +0000 en-US hourly 1 https://wordpress.org/?v=6.5 What is the return type of malloc()? https://beforebell.com/blog/2022/09/17/what-is-the-return-type-of-malloc/ https://beforebell.com/blog/2022/09/17/what-is-the-return-type-of-malloc/#respond Sat, 17 Sep 2022 18:41:15 +0000 https://beforebell.com/blog/?p=9 Read MoreWhat is the return type of malloc()?

]]>
Exams:

MAKAUT BTech CSE, 2017 (Marks: 1)

Answer:

void* (void type pointer).

Explanation

The malloc() is used to allocate memory at run-time. This is called dynamic memory allocation.

Both malloc(), and calloc() are used to get a chunk of free memory from the Operating System. These functions return the starting address of such a chunk or block of memory. The program code needs to typecast this chunk as per it’s needs.

Example:

The following code snippet shows how a node is created for a singly linked linear list.

// Code to define a simple node structure for a Singly Linked Linear List
struct NODE{
char data;
struct NODE *ptr;
}
typedef struct NODE node;

// Function to create a new node. The node is loaded with the given value in 
// the data field and Null in the link field by default.
node* createNode(char value){
    node* temp;
    temp = (node *)malloc(sizeof(node));
    if( temp==NULL )
        return NULL;
    temp->data = value;
    temp->ptr = NULL;
    return temp;
}

Related Question:

  1. What is the return type of calloc()?
  2. Why do we need to typecast the return value of malloc()?

]]>
https://beforebell.com/blog/2022/09/17/what-is-the-return-type-of-malloc/feed/ 0 9