Buffer-overflow safe readlink() in C++

Problem:

You want to use readlink() to get the file or directory a symbolic link points to, but you don’t know the buffer size that is required to store the symlink destination. You don’t want to allocate an incredibly large amount of memory (whatever amount you choose, it could always be insufficient), but you won’t risk buffer overflows.

Solution: readlink() returns -1 with errno == EINVAL if the buffer is too small. Therefore, you can simply call readlink iteratively with increasing buffer sizes.

This implementation uses std::string and returns an empty string in case of error (errno is still set in that case). If the file is no symlink, the filename argument is returned.

 


Check out similar posts by category: C/C++