CodeBlanks Logo Icon CodeBlanks

Error return values

  • C course
  • Intermediate
  • Lesson 57/116
  • 5 min

Learn error return values from functions.

Error return values

Many C functions report failure by return value. fopen returns NULL, malloc NULL, fgetc EOF, printf a negative number, and main a non-zero value. Using the return value without checking is undefined behavior.

The good habit: make the call, test the result, handle the error. On error, either return upward or print with perror and continue. Read the library docs to know which value each function returns; each function picks its own value.

Error propagation patterns

When a function catches an error, you have two choices: propagate upward or handle it. To propagate, make the error the return value: int read_config(void) { ... return -1; }. The caller checks again.

Handling means accepting the error and switching to an alternative: FILE *f = fopen("config.txt", "r"); if (!f) f = fopen("default.txt", "r");. Which one to choose depends on context: propagate critical errors, handle recoverable ones. Use consistent return values to avoid mixing them.

Practice Check the malloc result

Include <stdio.h> and <stdlib.h>. In main, allocate with int *p = malloc(sizeof(int));. If if (p == NULL), print printf("no memory\n"); and return 1;. Otherwise set *p = 42;, print printf("%d\n", *p);, and free with free(p);. End with return 0;.

Starter code

main.c
#include <stdio.h>
// Include stdlib.h

int main(void) {
    // Allocate an int with malloc
    // If NULL, printf and return 1
    // Else *p = 42, printf, free
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *p = malloc(sizeof(int));
    if (p == NULL) {
        printf("no memory\n");
        return 1;
    }
    *p = 42;
    printf("%d\n", *p);
    free(p);
    return 0;
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match function to its purpose

Term Meaning
fopen Opens a file
malloc Allocates memory
fgetc Reads a char
printf Prints text

2 What does malloc return on failure?

  • -1
  • EOF
  • NULL Correct answer
  • 0

Explanation: malloc returns NULL when it can't allocate memory.

3 Check the malloc result

Question
int *p = malloc(sizeof(int));
if (p == ____) { return 1; }
Answer
int *p = malloc(sizeof(int));
if (p == NULL) { return 1; }

Explanation: If malloc returns NULL, there's no memory.

All lessons in Intermediate