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; } 

    1 answer 1

    So, the second pass.

     if (index_path != NULL) 

    and it does not equal!

     { free(index_path); } 

    Freed memory. index_path points to a freed block of memory.

     index_path = realloc(index_path, strlen(path) + strlen(index[i]) + 1); 

    And we get in trouble - because the realloc pointer must be passed to the function realloc . And he points to the freed memory block.

    Reset index_path upon release ...

    And in general - why do you use realloc , and not malloc - if you still free up memory? Just use malloc ...

    • thanks, earned. Yes, in this case you can malloc. I removed the release of memory and left realloc. - Sibkedr
    • Could be so. The main thing is not to use an incorrect pointer. - Harry