无法重现 mallopt(M_PERTURB, 256) 与 MALLOC_PERTURB_=256 的效果

问题描述 投票:0回答:1

我正在寻找一种使用

MALLOC_PERTURB_
将统一化双精度填充为 nan 的方法。

这样做,我注意到当设置为 256 时

mallopt
MALLOC_PERTURB_
之间存在差异。根据文档,它们应该是等效的。

考虑以下代码,如果我导出

MY_MALLOC_PERTURB_
,它会调用
mallopt
:

#include <iostream>
#include <stdlib.h>
#include <malloc.h>


void print_uninitialized_memory(){
  char* mperturb = getenv("MY_MALLOC_PERTURB_");
  if (mperturb) {
    mallopt(M_PERTURB, atoi(mperturb));
  }

  int* i = new int;
  long* l = new long;
  float* f = new float;
  double* d = new double;
  void** p = new void*;

  std::cout << "with PERTURB = " << (mperturb? mperturb:"unset") << std::endl;
  std::cout << "  undefined int: '" << *i << "'" << std::endl;
  std::cout << "  undefined long: '" << *l << "'" << std::endl;
  std::cout << "  undefined float: '" << *f << "'" << std::endl;
  std::cout << "  undefined double: '" << *d << "'" << std::endl;
  std::cout << "  undefined pointer: '" << *p << "'" << std::endl;
}


int main() {
  print_uninitialized_memory();
  return 0;
}

使用任意值 0..255,

mallopt
MALLOC_PERTURB_
将分配的内存设置为相同的值:

$ MY_MALLOC_PERTURB_=2 ./a.out
with PERTURB = unset
  undefined int: '-33686019'
  undefined long: '-144680345676153347'
  undefined float: '-4.22017e+37'
  undefined double: '-7.84591e+298'
  undefined pointer: '0xfdfdfdfdfdfdfdfd'
$ MALLOC_PERTURB_=2 ./a.out
with PERTURB = 2
  undefined int: '-33686019'
  undefined long: '-144680345676153347'
  undefined float: '-4.22017e+37'
  undefined double: '-7.84591e+298'
  undefined pointer: '0xfdfdfdfdfdfdfdfd'

但是对于 256:

$ MY_MALLOC_PERTURB_=256 ./a.out
with PERTURB = 256
  undefined int: '-1'
  undefined long: '-1'
  undefined float: '-nan'
  undefined double: '-nan'
  undefined pointer: '0xffffffffffffffff'
$ MALLOC_PERTURB_=256 ./a.out
with PERTURB = unset
  undefined int: '0'
  undefined long: '0'
  undefined float: '0'
  undefined double: '0'
  undefined pointer: '0'

是否可以使用环境变量

MALLOC_PERTURB_
将双精度数初始化为-nan?

如果相关,已使用 glibc-2.28 和 2.35 进行了测试。

c++ unix malloc glibc
1个回答
0
投票

从这个文档https://www.gnu.org/software/libc/manual/html_node/Tunables.html,环境变量似乎有一个硬编码的 max=255:

$ /lib64/ld-linux-x86-64.so.2 --list-tunables
...
glibc.malloc.perturb: 0 (min: 0, max: 255)

这个最大值在 glibc 中的某处强制执行(可能在 dl-tunables.cdl-tunables.list:42 中)。

这也可以解释为什么值 257 对于

MALLOC_PERTURB_
表现为 255,对于
mallopt
表现为 1。

© www.soinside.com 2019 - 2024. All rights reserved.