c - 为什么在使用 mmap 时会附加额外的字符 ^@?

标签 c linux memory-management posix mmap

我尝试了一个简单的 mmap 相关的 C 代码片段:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
  int fd;
  char* mapped_mem;
  int flength = 1024;
  void* start_addr = 0;

  if (argc < 2) {
    printf("usage: %s filename\n", argv[0]);
    exit(1);
  }

  fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  flength = lseek(fd, 1, SEEK_END);
  write(fd, "\0", 1);

  lseek(fd, 0, SEEK_SET);
  printf("fd=%d, flength=%d\n", fd, flength);
  mapped_mem = mmap(start_addr, flength, PROT_READ, MAP_PRIVATE, fd, 0);

  printf("%s\n", mapped_mem);
  close(fd);
  munmap(mapped_mem, flength);

  return 0;
}

但是我发现每次我在数据文件上执行它时,^@^@ 都会附加到这个文件上。那么这是怎么回事?

最佳答案

您的程序首先将文件末尾移动 1 个字节(使用 lseek),然后在那里写入一个零字节(使用 write)。实际上,两个零字节附加到您的文件,其中一个字节填充文件末尾和写入位置之间的空白。

mmap 在这方面没有任何改变。损害已经造成。

关于c - 为什么在使用 mmap 时会附加额外的字符 ^@?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519638/

相关文章:

jqgrid - 使用 JQuery .bind() 的浏览器内存使用情况比较 : inline onClick vs.

c - 变量混淆

c - 如何在函数声明语句中使用二维数组?

linux - "/proc/$pid/latency"文件有什么作用?

.net - 了解 .Net Core 和 Mono

c++ - 为 C/C++ 标准库、boost 和第三方库设置单独的 ctags 数据库

c - scanf 不会以十六进制值终止?

c - 在 C 项目中包含 json-c

c - 我想得到 4 个单独的打印 : "This is a thread 1", "This is a thread 2"等等

c - *** 错误 `./prog5' : double free or corruption (out): 0x0000000001cc3260 *** Aborted (core dumped)