cbufferlow-level-io

Allocating and initializing a buffer with file data using a single loop


I try to read a file to a buffer using a low level file descriptor. The method suppose to store the file data byte by byte to a char * buffer, parse that data, and then free the allocated buffer.

static void
parse_file(char path[11]) {
  int fd = open(path, O_RDONLY);
  if (fd == -1) {
    fprintf(stderr, "Failed to open a file '%s'", path);
    exit(errno);
  }
  char c;
  char *buffer = {0};
  unsigned int i = 0;
  while (read(fd, &c, 1)) {
    buffer = malloc(sizeof(char));  // Why *buffer want work here?
    *buffer = c;
    ++buffer;
    ++i;
  }
  buffer = malloc(sizeof(char));
  *buffer = '\0';
  buffer = &buffer[0];
  printf("Buffer data:\n%s\n", buffer);

  // Parse buffer data
  // ...
  
  buffer = &buffer[0];
  for (unsigned int j = 0; j <= i; ++j) {
    free(buffer);
    ++buffer;
  }
}

I come up with the above solution, but flycheck gives me a warning of unix.Malloc type:

Attempt to free released memory

How can I allocate the buffer char by char in a single loop?


Solution

  • Construction like buffer = &buffer[0]; won't work. After the loop (and setting \0) buffer points to the last character (so to \0). Taking address of the 0th element will just give you address of the last element (as the buffer points). You cannot 'rewind' to the first character that way. When you call then free() you start freeing from your last element and then iterate over some memory region that was not allocated before.