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?
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.