循环malloc.c的矢量分段错误:没有这样的文件或目录

Segmentation fault in vector for loop-malloc.c: No such file or directory

本文关键字:文件 malloc 错误 分段 循环      更新时间:2023-10-16

我在下面的代码中遇到了背包问题贪婪算法的分段错误。我以前从未成功地解决过分割故障,尽管我见过它们,所以我很感激你的帮助。

当我运行调试器时得到的消息是没有"malloc.c"。当我运行valgrind时,我得到一个"大小为4的无效读取"。在这和bug的性质之间,我猜我正在尝试访问一个不存在的向量元素。但我已经尝试了我能想到的一切方法,试图确保循环在迭代向量时不会越界。

(我在没有使用基于C++11范围的for循环的情况下完成了这项工作,但仍然会得到相同的错误。我选择for循环的参数似乎并不重要,它仍然会抛出分段错误。)

提前谢谢。

#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
using namespace std;
bool decreaseSort(int a, int b)
{
   return a > b;   //sort by decreasing value for better performance
}
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
sort(weights.begin(),weights.end(), decreaseSort); 
sort(values.begin(),weights.end(), decreaseSort);
vector<int> ourKnapsack(values.size(), 0);
double totalValue = 0.0;
int ourInput = 0;
for (auto i : ourKnapsack){
  int ourValue = values.at(i);
  int ourWeight = weights.at(i);
  double unitValue = (double)ourValue/ourWeight;
  if (capacity == 0) 
      return totalValue;

  if (weights.at(i) < capacity){
      ourInput = weights.at(i);
  }
  else {
      ourInput = capacity;
  }

  totalValue = totalValue * (ourInput * unitValue); 
  weights.at(i)-=ourInput;
  ourKnapsack.at(i)+=ourInput;
  capacity-=ourInput;
 }
 return totalValue;
}
  int main() {
  int n = 3;
  int capacity = 50;
  vector<int> values(n);
  values = {60,100,120};
  vector<int> weights(n); 
  weights = {20,50,30};
  double optimal_value = get_optimal_value(capacity, weights, values);
  std::cout.precision(10);
  std::cout << optimal_value << std::endl;
  return 0;
}
sort(values.begin(),weights.end(), decreaseSort);

这就是你的问题,就在那里。哎呀。

显然,它应该是values.end(),而不是weights.end()