使用单个循环分配和初始化文件数据初始化缓冲区

发布于 2025-02-10 16:42:27 字数 910 浏览 3 评论 0原文

我尝试使用低级文件描述符将文件读取到缓冲区。该方法假设通过字节将文件数据字节存储到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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜心小果奶 2025-02-17 16:42:27

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文