【问题标题】:Resolving munmap warning message解决 munmap 警告消息
【发布时间】:2017-06-05 17:00:12
【问题描述】:

我正在编写一个程序,并获得了一个存储为 unsigned int 的内存位置,并且映射的长度为 unsigned int,我想取消映射。

我的以下方法会产生警告:

warning: passing argument 1 of ‘munmap’ makes pointer from integer without a cast [enabled by default]

/usr/include/i386-linux-gnu/sys/mman.h:77:12: note: expected ‘void *’ but argument is of type ‘unsigned int’

这引起了我的警告:

//startAddr and addrRange are stored as an unsigned int, 
void unmap(mapping_t *maps, const int *curSize){
  int i = 0;
  for (; i < *curSize; i++){
     munmap(maps[i].startAddr, maps[i].addrRange);   
  }
}

当我点击 munmap 时,我的程序也会崩溃,但我假设它必须以某种方式处理警告

根据要求定义 struct mapping_t:

typedef struct mapping{
  unsigned int startAddr;
  unsigned int endAddr;
  unsigned int addrRange;
} mapping_t;

【问题讨论】:

  • 发布mapping_t的定义。我当然希望你不会真正将指针值填充到 unsigned int 中。
  • 编译器肯定认为他是

标签: c memory-management mmap


【解决方案1】:

我正在编写一个程序并获得了一个内存位置,我已将其存储为无符号整数

不要那样做。使用void *char *,甚至[u]intptr_t。不要将指针塞入unsigned int。那是错的。指针不是int 值,可能无法由int 正确表示,这就是您收到警告的原因。根据 C 标准,允许将指针转换为 int - 这就是为什么您会收到警告而不是实际错误的原因 - 但不能保证转换回指针值会产生相同的地址。

以及映射的长度作为无符号整数,我想取消映射。

也不要这样做。使用size_t

typedef struct mapping{
  void *startAddr;
  size_t addrRange;
} mapping_t;

您不需要endAddr,因为您有起始地址和大小。如果需要结束地址,则需要将startAddr 转换为char * 来计算结束地址。

【讨论】:

  • 如果我改为输入void*,我将如何将unsigned int 读入我的startAddr?我改变了读取值的方式,如下所示:sscanf(line, "%x-%x %s", (unsigned int*)maps[*curSize].startAddr, ...) 但它导致我的程序现在在我尝试时崩溃
  • “将unsigned int 读入我的startAddr(带有scanf)”也是在几个层面上都是一个设计错误。最重要的是,进程 A 中的映射地址是 mmap 返回给进程 A 的地址,不是无论进程 B 认为它是什么。其次,如果您的代码对性能至关重要,足以打扰共享内存,那么对您的 IPC 消息使用二进制序列化也是值得的。最后,never use scanf for anything.
【解决方案2】:

您不能将 unsigned int 用于指针。使用 void *。

    typedef struct mapping{
      void * startAddr;
      void * endAddr;
      unsigned int addrRange;
    }   
mapping_t;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多