我目前正在开发一个解决背包问题的程序,必须使用指向矩阵的指针。使用伪代码后,我在学校被给了我,但我仍然收到分段错误,根据valgrind,这是原因:
1 errors in context 1 of 2:
==10545== Invalid write of size 4
==10545== at 0x4009C3: DP (dp.c:70)
==10545== by 0x400914: main (dp.c:39)
==10545== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==10545==
==10545==
=
=10545== 1 errors in context 2 of 2:
==10545== Use of uninitialised value of size 8
==10545== at 0x4009C3: DP (dp.c:70)
==10545== by 0x400914: main (dp.c:39)
==10545==
我试图使用过去的答案来解决问题,但我似乎无法弄清楚。在学校中的其他人也做过同样的事情,他们似乎没有收到此问题。我在代码中看不到或没有意识到有什么错误吗?
int **V, **keep; // 2d arrays for use in the dynamic programming solution
// keep[][] and V[][] are both of size (n+1)*(W+1)
int i, w, K;
// Dynamically allocate memory for variables V and keep
V = (int**)malloc((n+1) * (W+1) * sizeof(int*));
keep = (int**)malloc((n+1) * (W+1) * sizeof(int*));
// set the values of the zeroth row of the partial solutions table to zero
for (w = 0; w <= W; w++)
{
V[0][w] = 0;
}
// main dynamic programming loops , adding one item at a time and looping through weights from 0 to W
for (i = 1; i <= n; i++)
for (w = 0; w <= W; w++)
if ((wv[i] <= w) && (v[i] + V[i-1][w - wv[i]] > V[i - 1][w]))
{
V[i][w] = v[i] + V[i-1][w-wv[i]];
keep[i][w] = 1;
}
else
{
V[i][w] = V[i-1][w];
keep[i][w] = 0;
}
K = W;
for (i = n; i >= 1; i--);
{
if (keep[i][K] == 1)
{
printf("%d\n", i);
K = K - wv[i];
}
}
return V[n][W];
}
最佳答案
V = (int**)malloc((n+1) * (W+1) * sizeof(int*));
...
for (w = 0; w <= W; w++)
{
V[0][w] = 0;
}
malloc
调用中提供的大小没有意义。而且您从未初始化V[0]
(或与此相关的任何V[i]
)。它包含一个垃圾值。但是,您尝试访问V[0][w]
(以及以后的V[i][w]
)。这是未定义的行为。如果打算将
V
用作2D数组,请首先allocate it properly。关于c - 地址0x0未堆栈,未分配或(最近)未释放,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42870413/