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?