0

I can't seem to find a problem in my load and indexes function. I need help asap. PS- my lookup and parse functions show all green ticks on check50

 char* indexes(const char* path)
 {
   // TODO
     int length = strlen(path);
     char* copy = malloc(length + 13);
     strcpy(copy,path);
     strcat(copy,"/index.html");

     if(access(copy, F_OK) != -1)
       return copy;

     else
        free(copy);

   char* copy2 = malloc(length + 13);
   strcpy(copy2,path);
   strcat(copy2,"/index.php"); 

   if(access(copy2, F_OK) != -1)
    return copy2;

    else
     free(copy2);

    return NULL;
  }


    bool load(FILE* file, BYTE** content, size_t* length)
   {
      int i=0;
      // TODO
      char* buffer = malloc(sizeof(BYTE));
      *length =0;
      while(!feof(file))
      {
          if(file == NULL)
          return false;

          buffer[i] = fgetc(file);

          buffer = realloc(buffer,++i);
          *length = *length + sizeof(BYTE);
         }

         *content = buffer;
         return true;
      }

1 Answer 1

2

Reread the specification for indexes in the instructions.

Complete the implementation of indexes in such a way that the function, given a /path/to/a/directory, returns /path/to/a/directory/index.php if index.php actually exists therein, or /path/to/a/directory/index.html if index.html actually exists therein, or NULL. In the first of those cases, this function should dynamically allocate memory on the heap for the returned string.

Order is important.

load

buffer is always going to be reallocated for 1 less byte than you need. Let's look at the first pass:

  1. i is 0
  2. buffer is allocated for one byte
  3. put the first byte of file into the first byte of buffer (buffer[0])
  4. reallocate buffer to ++i bytes. Which is? 1 byte!

But wait, there's more!

Rewatch Week 4 > Shorts > File I/O. Around 8:30 Jason discusses the pitfalls of while(!feof(file)).

Here's a test scenario you can try to help you use gdb to debug your load function.

  1. create a small test file in public, a.html. Populate it with 'a'. Verify the length with ls -al a.html. (I created such a file with vi and it is 2 bytes. That ls command reports
    -rw------- 1 ubuntu ubuntu 2 Aug 19 14:14 a.html where 2 is the number of bytes).
  2. start a "gdb ./server" session in a terminal tab, and set a break at load. (tips here)
  3. in another terminal tab issue a curl request for a.html (curl -i http://localhost:8080/a.html)
  4. Meanwhile, back at the gdb terminal, it should be waiting at the load function.
  5. Now you can step your way through the function and inspect all the variables. It is important that *length be exactly the same as the number of bytes reported in ls when control returns to main.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .