cpointersstructintegerincompatibletypeerror

How to return a error code from a function which creates structures dynamically


I return a error code from create_node function so that if memory not available it returns to the main and the program ends. I get an error that comparison of integer to pointer. Can you please help me to deal with it. I am a beginner. Thanks.


node *create_node(void)
{
    node *newnode = (node *)malloc(sizeof(node));

    if (newnode == NULL)
        return 1;
    newnode->right = NULL;
    newnode->left = NULL;
    return newnode;
}
int main(void)
{
    int ret_val = 0;
    node *root = create_node();

    if (root == 1) {
        printf("Memory not available to create a node\n");
        return 0;
    }
    root->left = create_node();
    if (root->left == 1) {
        printf("Memory not available to create a node\n");
        return 0;
    }
    root->right = create_node();
    if (root->right == 1) {
        printf("Memory not available to create a node\n");
        return 0;
    }
}

Solution

  • According to the C Standard (6.5.9 Equality operators) relative to comparisons of pointers and integers there is written

    2 One of the following shall hold:

    — both operands have arithmetic type;

    — both operands are pointers to qualified or unqualified versions of compatible types;

    — one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or

    — one operand is a pointer and the other is a null pointer constant.

    So you may not compare a pointer and an integer without casting.

    But in any case there is no need to return an integer in the case when a memory allocation will fail. In such a case it is enough to return NULL.

    So the function can look like

    node * create_node(void)
    {
        node *newnode = malloc( sizeof( node ) );
    
        if  ( newnode != NULL )
        {
            newnode->right = NULL;
            newnode->left  = NULL;
        }
    
        return newnode;
    }
    

    Thus in main you can write for example

    node *root = create_node();
    
    if ( root == NULL ) {
        printf("Memory not available to create a node\n");
        return 0;
    }
    

    without getting the error message of the compiler.