0

I'm making a simple binary tree. I have a function that allocates memory for a root node and returns a pointer to that memory. I was careless and forgot to return the pointer at the end of the function. The thing is, that when I tested the function in main, somehow the pointer was actually returned. The code is:

struct node
{
    int key;

    struct node* lc;
    struct node* rc;
};

struct node* init_root(int key)
{
    struct node *root;
    root = (struct node*)malloc(sizeof(struct node));
    root->key = key;
    root->lc = NULL;
    root->rc = NULL;
}

int main()
{
    struct node* root;

    root = init_root(60);

    printf("%d\n", root->key);

    return 0;
}

Why the correct value I want to print is printed even if I dont return explictly the pointer?

Steve Friedl
  • 3,929
  • 1
  • 23
  • 30
  • 6
    A function with a return type different then `void` without a `return` statement invokes [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). (except `main` function, `main` returns 0 "by default"). – KamilCuk Apr 27 '20 at 13:11
  • 1
    Don't cast malloc. https://stackoverflow.com/a/605858/1216776 – stark Apr 27 '20 at 13:12
  • 4
    Does this answer your question? [Function returns value without return statement](https://stackoverflow.com/questions/4644860/function-returns-value-without-return-statement) or maybe https://stackoverflow.com/questions/32513793/c-and-c-functions-without-a-return-statement is better – KamilCuk Apr 27 '20 at 13:14
  • 1
    The function will appear to return whatever happens to be in the thing (probably a particular register) that is normally used to return values of the function's return type. – Ian Abbott Apr 27 '20 at 13:17

0 Answers0