The perror() function is a built-in C function used to print a custom error message followed by the system-generated error description based on the value of the global errno variable.
- Displays a user-defined message along with the corresponding system error.
- Commonly used to identify the cause of errors after a function fails.
#include <stdio.h>
int main() {
FILE *fp = fopen("missing.txt", "r");
if (fp == NULL) {
perror("Error");
return 1;
}
fclose(fp);
return 0;
}
Output
An error occurred: No such file or directorySyntax
clearerr() is a standard library function defined in <stdio.h> file.
void perror(const char *message);
This function does not return any value.
Examples of perror()
The following examples demonstrate the use of perror() in our C programs:
Handle Memory Allocation Error
#include <stdio.h>
#include <stdlib.h>
int main() {
size_t size = 1e18;
void *ptr = malloc(size);
if (ptr == NULL) {
// Print memory allocation error using
// perror()
perror("Memory allocation failed");
}
else {
free(ptr);
}
return 0;
}
Output
Memory allocation failed: Cannot allocate memoryHandle Insufficient Permission Error
#include <stdio.h>
int main() {
FILE *file = fopen("/root/protected.txt", "w");
if (file == NULL) {
perror("Error creating file");
return 1;
}
fclose(file);
return 0;
}
Output
Error creating file: Permission deniedCommon Functions Used with perror()
perror() is often used with functions that set errno when they fail.
- fopen(): File opening errors.
- malloc(): Memory allocation failures.
- remove(): File deletion errors.
- rename(): File renaming errors.
Advantages
The perror() function provides a simple way to display descriptive error messages, making debugging easier.
- Prints a meaningful system-generated error message.
- Helps quickly identify the cause of function failures.
- Easy to use with file handling and memory allocation functions.
Limitations
Although useful, perror() has some limitations that should be considered while handling errors.
- Depends on the value of the global errno variable.
- Prints the error message directly to stderr.
- Should be called immediately after the error occurs, before errno changes.
perror() Vs strerror()
| perror() | strerror() |
|---|---|
Prints the error message directly to the standard error stream (stderr). | Returns the error message as a string. |
| Takes a custom message as an argument. | Takes an error number (such as errno) as an argument. |
| Does not return any value. | Returns a pointer to the corresponding error message. |
| Best suited for quick error reporting. | Useful when the error message needs to be stored, formatted, or processed. |