【问题标题】:Error deleting an array while porting code from Windows to Linux将代码从 Windows 移植到 Linux 时删除阵列时出错
【发布时间】:2012-12-26 23:09:31
【问题描述】:

我正在尝试将在 Windows 中正常工作的库移植到 Linux。

在这些代码行中我得到一个错误:

long* permutation = new long[result->getGeneListCount()];
for(long i=0; i<result->getGeneListCount(); i++) 
        permutation[i]=i;
Util::ArrayUtil::DurstenfeldArrayPermutation<long>(permutation, result->getGeneListCount()); 

//result->PerformGenePermutation(permutation);
std::cout << "Just skipped the permutation" << std::endl;

delete[] permutation;

在我看来,错误似乎是在删除期间发生的。我知道,既然我已经评论了PerformGenePermutation(),我可以简单地评论其他行,但是类似的问题可能会再次出现在其他代码中,所以我想了解错误。

我得到的错误输出是:

*** glibc detected *** /usr/lib/jvm/java-7-oracle/bin/java: munmap_chunk(): invalid pointer: 0x09f287f8 ***

有人可以帮帮我吗?

如果您需要更多详细信息,请询问我。

【问题讨论】:

  • 有没有可能result-&gt;getGeneListCount() retuns 0
  • permutation 指针不会改变对DurstenfeldArrayPermutation 的调用吗?您能否通过在调用前后打印指针值 (printf("%p\n", permutation);) 来验证这一点? DurstenfeldArrayPermutation 会自行释放指针吗?
  • DurstenfeldArrayPermutation 是否通过引用获取其第一个参数?如果是这样,它可能会尝试重新分配它,这在某些平台上可能很好(mallocnew[] 用户使用相同的底层分配器)但在其他平台上则不然。
  • @ahenderson:我试过了,它不返回 0!
  • @ulidtko :我检查了,但排列的值在函数之后没有改变。

标签: c++ linux porting


【解决方案1】:

给定的代码和信息不足以确定问题的原因,但您可以执行以下操作:

替换代码

long* permutation = new long[result->getGeneListCount()];
for(long i=0; i<result->getGeneListCount(); i++) 
        permutation[i]=i;
Util::ArrayUtil::DurstenfeldArrayPermutation<long>(permutation, result->getGeneListCount()); 

//result->PerformGenePermutation(permutation);
std::cout << "Just skipped the permutation" << std::endl;

delete[] permutation;

std::vector<long> permutation( result->getGeneListCount() );
for(long i=0; i<long(permutation.size()); i++) 
        permutation[i]=i;
Util::ArrayUtil::DurstenfeldArrayPermutation<long>(&permutation.at( 0 ), permutation.size()); 

//result->PerformGenePermutation(permutation);
std::cout << "Just skipped the permutation" << std::endl;

//delete[] permutation;

请注意,delete 已被删除,因为 std::vector 会自动为您执行此操作。

如果现在从std::vector::at 的范围错误中抛出异常,那么您知道大小可能为零。无论如何,您现在可以非常简单地在调试器中检查它。更重要的是,如果它确实没有抛出异常,那么你就知道这段代码一切都很好(因为std::vector 是可靠的),那么问题就出在其他地方了。

很遗憾,这篇文章太长了,无法作为评论发布,但它并不是真正的答案。这是 SO 的问题。由于它是为纯粹的答案而设计的,因此不支持一般的帮助

【讨论】:

  • 嗯,它奏效了。没有抛出异常。现在对我来说已经足够了:)
猜你喜欢
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多