c++ - dynamic programming, coin change, memory leak? -
i writing program change coin. when write printf in loops print or j program give results, when delete it, program stops. think it's problem memory i'm writing on windows in qt , have no access valgrind.
anyone can check this? first give numbers of denomination, second - denominations, last amount.
e.g:
3 1 3 5 8
result should 2.
1 5 3
result sholud no.
#include <stdio.h> #include <stdlib.h> #define inf 2147483647 //nieskonczonosc void nominal(int nominaly, int t[], int k) { int i; (i=1; i<=nominaly; i++ ) { int n=0; scanf("%d", &n); int j; ( j=0;j<=k-n;++j) { if (t[j] < inf) if (t[j]+1 < t[j+n]) t[j+n] = t[j]+1; } } int kwota=0; scanf("%d", &kwota); if(t[kwota]==inf){ printf("no"); }else printf("%d", t[kwota]); } int main() { int n=0; scanf("%d", &n); int k=10000; int *t; t = (int*)malloc(k * sizeof(int)); t[0]=0; int i; (i=1;i<=k;++i) { t[i]=inf; } nominal(n, t, k); free(t); return 0; }
assuming input well-formed, problem can spot in code in these lines:
if (t[j]+1 < t[j+n]) t[j+n] = t[j]+1;
when j
reaches value k-n
, t[j+n]
out-of-bounds access, because k-n+n
, accessing t[k]
, , last valid position t[k-1]
. invokes undefined behavior in program - (including working expected) can happen.
you might want rewrite for
loop like:
for (j=0; j < k-n;++j) { ... }
there no memory leaks in code.
Comments
Post a Comment