'Properly appending line to a buffer in a loop

I'm going through the excellent nand2Tetris course and building an assembler to transform assembly language to machine code. Given a program like so:

// Computes R0 = 2 + 3  (R0 refers to RAM[0])

@2
D=A
@3      // this is a comment
D=D+A
@0
M=D

It must be converted to its corresponding binary:

0101001000001111
1101111000000001
0111001000001001
...

To do this, I'm first doing some pre-processing to remove comments and extra line breaks. Since I'm still a beginner in C, I'm having issues copying over the line to the resulting buffer.

instead of outputting the whole buffer (which should be the assembly program without empty lines or comments , I only get a part of it like so:

@2
D=A

Below is the whole function:

char *first_pass(FILE *fp) {
  int chunk = 4096;
  char *buffer = malloc(chunk);
  char *test = NULL;
  int mem_used = 0;

  if (!buffer) exit(1);

  char *line = NULL;
  size_t linecap = 0;
  int linelen;
  while ((linelen = getline(&line, &linecap, fp)) > 0) {
    if (*line == '/' || *line == '\n' || *line == '\r') {
      continue;
    } else {
      // check for comment in line
      int p = 0;
      while (line[p] != '/') {
        p++;
      }
//      if (line[p] == '/') {
//        // copy over line up to p
//      }
      mem_used += linelen;
      if (mem_used >= chunk) {
        chunk *= 2;
        test = realloc(buffer, chunk);
        if (!test) {
          free(buffer);
          exit(1);
        } else {
          buffer = test;
        }
      }
      // add line to buffer
      strlcat(buffer, line, sizeof(buffer));
    }
  }
  buffer[mem_used+1] = '\0';
  free(line);
  return buffer;
}

Would also appreciate if you can point out any style/bad practices you see in this program. Thank you.

c


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source