Return Code on failure. Positive or negative?

前端 未结 6 1110
野的像风
野的像风 2021-01-04 18:14

a C-programm can fail to execute under special circumstances in Linux. Example: You allocate some space and the OS denies it.

char *buffer = (char *) malloc         


        
6条回答
  •  难免孤独
    2021-01-04 18:44

    errno is a global variable you would set with the error number. The convention is to set errno and then return a negative number (usually negative one). The negative return value indicates errno should be checked. Using your example (and putting it into a function), it might look like this:

    int allocate_buffer(char *buffer) {
        buffer = malloc(1024);
        if (buffer == NULL) {
            errno = ENOMEM;
            return -1;
        }
        return 0;
    }
    

    The caller would then know if there was an error based on the return value, and check errno to see what the error was and decide how to proceed from there.

提交回复
热议问题