I am doing a learning task on CS50 - a server that responds to browser requests. I implement the indexes function - the path to the directory is transferred to it - something like: "/ home / ubuntu / workspace / pset6 / public /" - my function takes this path as a parameter and checks if the directory has an index.php file or. html returns the path with this file, i.e. "/home/ubuntu/workspace/pset6/public/index.html", if there is no such file, returns NULL.
At first he did everything consistently - everything worked. I decided to optimize, in order not to duplicate the lines of code, to get into a loop, but now on the 2nd pass of the loop when it gets to open the file, a segmentation error takes off.
char* indexes(const char* path) { char* index_path = NULL; FILE* file = NULL; char* index[2] = {"index.html", "index.php"}; for (int i = 0; i < 2; i++) { if (index_path != NULL) { free(index_path); } index_path = realloc(index_path, strlen(path) + strlen(index[i]) + 1); strcpy(index_path, path); strcat(index_path, index[i]); file = fopen(index_path, "r"); if (file != NULL) { fclose(file); return index_path; } } free(index_path); return NULL; }