CodeBlanks Logo Icon CodeBlanks

dlerror

Learn error handling with dlerror.

What is dlerror?

dlerror returns the error message of the last dlopen, dlsym or dlclose call. If there is no error, it returns NULL. Calling it clears the error state; so you should not call it twice in a row.

The correct pattern: first clear the old error with dlerror(), then do the operation, then get the new error with const char *e = dlerror();. If e is NULL, the operation succeeded; otherwise e is the error message. For testing, you can deliberately load a bad path and catch the error; the output printf("error caught\n") is deterministic.

The error catching pattern

For error catching: clear the old error with dlerror();. Load a deliberately bad path with void *h = dlopen("/no/such/path.so", RTLD_LAZY);. Get the error with if (!h) { const char *e = dlerror(); }. The error message is in e.

For testing, printf("error caught\n") is enough. In real apps you print or log e. The output is deterministic because printf always prints the same constant. The error message itself is environment-dependent; so we avoid printing it.

Practice Catch an error

Clear the old error with dlerror();. Load a bad path with void *h = dlopen("/no/such/path.so", RTLD_LAZY);. Get the error with if (!h) { const char *e = dlerror(); (void)e; }. Print with printf("error caught\n");.

Starter code

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

// Clear old error
// Load bad path
// Get error and print constant

int main(void) {
    return 0;
}

Sample solution

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

int main(void) {
    dlerror();
    void *h = dlopen("/no/such/path.so", RTLD_LAZY);
    if (!h) {
        const char *e = dlerror();
        (void)e;
    }
    printf("error caught\n");
    return 0;
}

Expected output

error caught

Questions and answers

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

1 What does dlerror return when there is no error?

  • Empty memory
  • Error code
  • File descriptor
  • NULL Correct answer

Explanation: dlerror returns NULL when there is no error.

2 Match dlerror parts

Term Meaning
dlerror Error message
NULL No error
clear Call first
const char * Return type

3 dlerror call

Question
const char *e = ____;
Answer
const char *e = dlerror();

Explanation: dlerror() gives the last error message.

All lessons in Advanced