Home > Mobile >  Malloc vs Creating a Data Structure
Malloc vs Creating a Data Structure

Time:10-01

What is the use of malloc, instead of just creating a structure within a c function? For example, this is the model code for creating a node in a Binary Search Tree.

void insertBSTNode(BTNode **node, int value)
{

    if (*node==NULL)
    {
        *node=malloc(sizeof(BTNode));
        (*node)->item =value;
        (*node)->left =NULL;
        (*node)->right = NULL;
        return;
    }
    if ((*node)->item > value)
        insertBSTNode(&((*node)->left), value);
    else if ((*node)->item <value)
        insertBSTNode(&((*node)->right), value);
    else
    {
        printf("Already exists in the BST\n");
        return;
    }
    return;
} 

I tried to do something similar, but instead created the struct instead like this:

void insertBSTNode(BTNode **node, int value)
{
    if ((*node) == NULL){
        BTNode insert;
        insert.item = value;
        insert.left = NULL;
        insert.right = NULL;
        (*node) = &insert;
        return;
    }   
    
    else {
        int Nodeitem = (*node)->item;
        if (value>Nodeitem){
            insertBSTNode(&((*node)->right),value);
            return;
        }

        if (value<Nodeitem){
            insertBSTNode(&((*node)->left),value);
            return;
        }
    }
}

But Nodeitem would always be the address instead. Why does malloc work in this case? When I use BTNode insert, is that not similar to using malloc instead whereby &insert just points to the memory location? Should I be using malloc instead then?

CodePudding user response:

When using BTNode insert; you are using memory from the stack. This is fine as long as you are only working with this data inside of the insertBSTNode function, but once you leave the function, the stack memory can (and will) be used by other functions. malloc on the other hand uses heap memory, so you can use the allocated memory outside of the function which called malloc without the risk of it being overwritten by other functions. You also have to keep in mind that memory allocated with malloc must be manually freed once it is no longer needed by your application.

  • Related