Home > Software engineering >  can i return a integer for int* return type in function
can i return a integer for int* return type in function

Time:07-25

i am making a function that allocates memory for an array and returns it and if malloc() fails then it return a int -1 to show it failed.

int *make_array() {

    int *array = malloc(sizeof(int) * 3);

    if (array == NULL)

       return -1;

    array[0] = 5;
    array[1] = 9;
    array[2] = 3;

    return array;


}

the return type is int* which is correct for the array BUT if it fails the -1 is returned which is not int*. is it acceptable to return -1 when return type is int* if not how could i make it correct?

CodePudding user response:

C standard has intptr_t (and uintptr_t) type which can accommodate any void pointer.

The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer

Unfortunately, it does not work in the opposite direction. Some intptr_t values might be trap representations if converted to a pointer.

In portable code you cant assume that (intptr_t)-1 can be converted to a void pointer.

Return NULL if function fails.

If you want to return some additional status information simply add an additional parameter

int *make_array(int *status) 
{
    int *result;

    /* some code */

    if(status) //caller might not need to know the status
    {
        *status = status_code;
    }
    return result; 
}

CodePudding user response:

You would need to check the return value in any case anyway – but the typical way to check a pointer is:

int* ptr = make_array();
if(!ptr)
{
    // error handling
}

If you have pointers as a return value then the general expectation is that you get a null pointer in case of errors – and you break this expectation by returning -1 converted to a pointer, thus produce a great surprise. Anything else but safe! Don't do that. Just don't do that.

If you want to be able to return error codes then do so explicitly! One possible variant might look as follows:

int make_array(int** target)
{
    *target = malloc(/*...*/);
    if(!*target)
    {
        return -1;
    }

    // ...

    return 0;
}

An alternative variant might return the pointer to array and accept a pointer to int to store an error code at: int* make_array(int* error_code), see @0___________'s answer.

Note, though, that in given case this information (both variants) is redundant and doesn't provide any more information than simply returning a null pointer, so I recommend rather sticking with the previous variant.

The error code style gets interesting as soon as you need to be able to distinguish various different error conditions, which doesn't seem to be the case here, though.

  • Related