Search code examples
cdynamic-memory-allocation

does a function automatically return dynamically allocated variable?


While Studing the Tree Data Structure, I came across this code which traverse the tree in preorder

#include <stdio.h>

#include <stdlib.h> 

struct node 
{ 
   int data; 
   struct node* left; 
   struct node* right; 
};

struct node* newNode(int data) 
{ 
    struct node* node = (struct node*)malloc(sizeof(struct node)); 
    node->data = data; 
    node->left = NULL; 
    node->right = NULL; 
    return node;
}
void printPreorder(struct node* node) 
{ 
    if (node == NULL) 
        return; 
    printf("%d ", node->data);
    printPreorder(node->left); 
    printPreorder(node->right); 
}    

int main() 
{ 
    struct node *root = newNode(1); 
    root->left   = newNode(2); 
    root->right = newNode(3); 
    root->left->left = newNode(4); 
    root->left->right = newNode(5);  
    printf("\nPreorder traversal of binary tree is \n"); 
    printPreorder(root); 
    getchar(); 
    return 0; 
  }

In the function newNode(int data), even if we remove the return statement the code works totally fine. So, my question is does the function newNode is automatically returning the node variable or something else is happening?

Any help is Appreciated. Thanks!


Solution

  • If a function is defined to return a value but fails to do so, and the calling function attempts to use the return value, you invoked undefined behavior.

    In your case, the program appeared to work properly. That's one of the ways undefined behavior can manifest itself. That could change with an unrelated change to your program, such as adding an extra local variable or a call to printf for debugging.

    If the function says it returns a value, you should ensure it always returns a value.