使用单个循环分配和初始化文件数据初始化缓冲区
我尝试使用低级文件描述符将文件读取到缓冲区。该方法假设通过字节将文件数据字节存储到char *
缓冲区,解析该数据,然后释放分配的缓冲区。
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;
}
}
我提出了上述解决方案,但是FlyCheck向我发出警告unix.malloc
类型:
尝试免费发布内存
我如何在char中分配char的缓冲区char单个循环?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像
buffer =&amp; buffer [0];
无法工作。循环后(和设置\ 0)缓冲区指向最后一个字符(SO \ 0)。取0个元素的地址只会为您提供最后一个元素的地址(作为缓冲区点)。您不能以这种方式“倒带”到第一个角色。当您致电时,
free()
您开始从最后一个元素释放,然后在某些以前未分配的内存区域上迭代。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.