c - Filling array gives unexpected values -
i have serious problem when filling array. functions looks this:
int s_in[]; /* array filled lot of integer values */ for(frame=0; frame<maxframes; frame++){ left = 240*(frame-1) + 1; right = 240*(frame +1); int x[right-left+1]; /* 480 long */ for(i=left-1;i<right;i++){ x[i] = s_in[i]; }
when try print out values stored in x[] each run, either empty x[] or random numbers not appear in s_in[]. can problem solved kind of memory management?
there 2 problems in line:
x[i] = s_in[i];
on first iteration, when aboce line executed, values of variables are:
frame: 0 left: -239 i: -240
the code attempts read outside of bounds of s_in[]
, write writes outside of bounds of x[]
.
this undefined behaviour.
it's difficult provide fix code without knowing how information laid out in s_in[]
. assuming frame 240 bytes , on each iteration want copy values 2 consecutive frames s_in[]
x[]
, code should along these lines:
int s_in[]; /* array filled lot of integer values */ (frame = 1; frame < maxframes; frame ++) { left = 240 * (frame - 1); /* first value of previous frame */ right = 240 * (frame + 1); /* first value of next frame */ int x[480]; /* 480 long */ (i = 0; < 480; ++) { x[i] = s_in[left + i]; } }
there no point in computing right-left+1
on each iteration since know must 480
. can see code above, value of right
not needed.
the outer loop should start frame = 0
frame #0
offending line attempts read outside s_in[]
; why starts frame #1
.
i suppose more processing inside inner loop. otherwise can replace call memcpy(&x, &s_in[left], 480);
. same current status of for
loop runs faster.
Comments
Post a Comment