0

when allocating memory, it is recommended to manually check whether the allocation was successful (or more accurately, terminate the program if it wasn't).

Main:

int main (void) 
{
    char *c = malloc(/*amount of memory to allocate*/);
    if (c == NULL) {
       printf("optional error message");
       return 1; 
    }
}

Any return value != 0, in the main function signals an error. Whatever return (error) value is given is arbitrary?

Void

void allocate()
{
    char *c = malloc(/*amount of memory to allocate*/);
    if (c == NULL) {
        printf("optional error message");
        return; 
    }
}

Will the function not exit without an error (ie except for the printed error message, the program will still run like the function ran successfully)?

Non void

int allocate()
{
    char *c = malloc(/*amount of memory to allocate*/);
    if (c == NULL) {
        printf("optional error message");
        return 1; 
    }
}

Will the function not exit without an error and return 1?

1 Answer 1

1

Here are my thoughts on your interesting question. It touches on the broader category of error handling.

Any return value != 0, in the main function signals an error. Whatever return (error) value is given is arbitrary?

To a large extent the return value is arbitrary. It (usually) only has meaning to the "caller". Recall the discussion of $? (testing the return value at the command line). If a user or another program executes your program and needs to know whether it was successful before proceeding, the error status can/should/will tell them that. In this example, the caller needs to know that if your program returns 1 it means memory could not be allocated. You could have returned 69 or 144 or 5862. As long as the caller knows it means memory could not be allocated, they can proceed accordingly.

To be more precise, a non-zero return value does not have to indicate failure. Once again, the caller needs to know what the return value means.

Will the function not exit without an error (ie except for the printed error message, the program will still run like the function ran successfully)?

Yes. The program that called allocate(); will print the error message and the function will exit, then hum along and process its (the caller's) next instruction. Chances of eventual failure might be high :)

Will the function not exit without an error and return 1?

Actually, methinks this function will not compile because there is no return for the true condition, so let's assume it returns 0 on success. If there is an error, the message will be printed and the function will return 1 to the caller. It would be up to the caller to handle program flow based on the result of allocate();

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .