Felix Rosén Felix Rosén - 4 months ago 8
C Question

Check if a file exists, given a directory to that file. How to debug?

So basically I'm given a path to a directory and should return

index.html
if it exists or
index.php
if that file exists. The thing is that I don't know how to debug this function since I'm only implementing this function for a much larger program.

char *indexes(const char *path) {
char *newPath = malloc(sizeof(char) * strlen(path));
strcpy(newPath, path);

if (access(path, F_OK)) {
if (access("index.html", F_OK)) {
strcat(newPath, "/index.html");
} else
if (access("index.php", F_OK)) {
strcat(newPath, "/index.php");
} else {
return NULL;
}
} else {
return NULL;
}
return newPath;
}


Does this look correct? When I run my program I get an error of
501 Not Implemented

Answer

Since you are going to concatenate path and /index.html into the newly allocated newPath, you must allocate it to at least the sum of lengths plus 1 extra byte for the null terminator:

strlen(path) + strlen("/index.html") + 1;

"/index.php" is shorter than the other string, so the buffer can handle the alternative concatenation.

The current code causes a buffer overflow, invoking undefined behavior, potentially causing the observed behavior.

Note that your code cannot work as written: you should concatenate before checking access, otherwise you check access in the wrong directory. You should also free(newPath); in case neither index file is found.

Here is a corrected version:

char *indexes(const char *path) {
    char *newPath = malloc(strlen(path) + strlen("/index.html") + 1);

    if (newPath) {
        strcpy(newPath, path);
        strcat(newPath, "/index.html");
        if (access(newPath, F_OK)) {
            return newPath;
        }
        strcpy(newPath, path);
        strcat(newPath, "/index.php");
        if (access(newPath, F_OK)) {
            return newPath;
        }
        free(newPath);
    }
    return NULL;
}
Comments