I am solving a 0-1knapsack problem. I solved the problem by brute force algorithm.
In main.cpp
int main(int argc, char *argv[])
{
......
int solution;
solution = bruteForce();
......
}
The strange thing is, when I implement the bruteForce() in main.cpp, my program works correctly, however, after I move the bruteForce() to bruteForce.cpp and included it in main.cpp, the program will produce segmentation fault when calling the bruteForce().
Here's how I move bruteForce() to bruteForce.cpp. First I created a header functions.h(because I want to solve the problem by other method after implement brute force successfully)
functions.h:
#include "global.h"
int bruteForce();
int multiplication( int );
And then I move bruteForce() to bruteForce.cpp
#include <iostream>
#include <stdlib.h>
#include <vector>
#include "global.h"
#include "functions.h"
using namespace std;
int bruteForce()
{
int bestValue = 0;
int j, tempSize, tempValue;
int bestChoice[n+1];
for(int i=0; i<multiplication(n); i++)
{
tempSize = 0;
tempValue =0;
j = n;
while(x[j]!=0 && j>0)
{
x[j] = 0;
j--;
}
x[j] = 1;
for(int k=1; k<=n; k++)
{
if(x[k] == 1)
{
tempSize += size[k];
tempValue += value[k];
}
}
if((tempValue > bestValue) && (tempSize <= S))
{
bestValue = tempValue;
for(int p=1; p<=n; p++)
bestChoice[p] = x[p];
}
}
for(int p=1; p<=n; p++)
x[p] = bestChoice[p];
return bestValue;
}
In global.h, I declared some glabal variables:
#include <vector>
using std::vector;
static int n, S;
static vector<int> value, size, x;
The gdb debugger shows
Program received signal SIGSEGV, Segmentation fault.
0x08049308 in main()
Any idea about why this happens?
Thanks in advance.
Oh BTW, if you need more info, here's the package. You can first type make in the root of this package. Then type this to execute.
./bin/01knapsack -BF inputs/n5S11.in n5s11.out