【问题标题】:Why would this give a Use of uninitialised value of size 8为什么这会给出大小为 8 的未初始化值的使用
【发布时间】:2020-02-08 03:35:23
【问题描述】:

在我的代码中,我有一个名为membrane 的类,一个名为exciteMod() 的函数,一个名为decide() 的函数和一个名为delta_U 的变量。 exciteMod() 的第一行是this->delta_U = 0。在decide() 中,我的指数为-delta_U (exp(-this->delta_U))。这会导致错误使用大小为 8 的未初始化值。什么可能导致这种情况?我对 valgrind 中生成的 delta_U 没有任何错误。

编辑: 以下是相关代码段:

void membrane::exciteMod(){
  this->delta_U = 0;
  /* Do some stuff which does not directly affect this->delta_U*/
  std::tr1::shared_ptr<bead> bit = this->beads.begin();
  while (bit != this->nead.end()){
    std::tr1::shared_ptr<bead> b = *bit++;
    //calculate the doubles U and nextU on b, nothing here gives a warning in valgrind,     anyhow U and nextU on b are always defined
   this->delta_U += (b->nextU - b->U);
  }
  decide();
}

void membrane::decide(){
  double r = P.r.ran3() // the random function from numerical recepies
  double f = - this->delta_U;
  if (r > exp(f)){ //this gives the warning even though delta_U is valid
    /*stuff*/
  }
}

这是警告:

==467== 使用大小为 8 的未初始化值
==467== 在 0x300B00D75D:__ieee754_exp(在 /lib64/libm-2.5.so 中)
==467== by 0x300B022FA3: exp (in /lib64/libm-2.5.so)
==467== by 0x40BB9A:membrane::decide() (membrane.cpp:813)
==467== by 0x40EBB1:membrane::exciteMod() (membrane.cpp:639)
==467== by 0x413994:membrane::MCstep(int) (membrane.cpp:486)
==467== by 0x402767: main (main.cpp:14)

编辑:
我应该提到我打电话给decide()的唯一地方是exciteMod()内部。

【问题讨论】:

  • 顺便说一句,您不需要this-&gt; 语法来访问成员函数中的成员变量。直接访问它们:delta_u = 0;

标签: c++ valgrind


【解决方案1】:

值未初始化的最可能原因是您添加到delta_Ub-&gt;nextUb-&gt;U 中的至少一个本身未初始化。那就是:

foo = 0;
foo += some_uninitialized_value;
if (foo)  // Valgrind warns here

您希望 Valgrind 在 foo 未初始化时报告。不幸的是,这样做会产生太多“误报”警告,不实用。

您可以在循环中插入对VALGRIND_CHECK_MEM_IS_DEFINED 的调用(请参阅Valgrind user manual),当delta_U 变为未定义时,Valgrind 会发出确切的信号。

【讨论】:

  • 是的,我昨晚很晚才发现这个。我不明白为什么这是抛出错误的地方和以前的地方。
【解决方案2】:

假设您有 t 个值需要存储。然后使用这个:

int *p = (int *) malloc(t*(sizeof(int)+1));
memset(p,0,t*(sizeof(int)+1));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多