c - Program misbehaves 25% of the time -
inspired this topic, decided write simple program that.
logic isn't complicated , have working program 75% of time.. amount of asked numbers defined #define bufsize x
, x
can arbitrary int.
problem arises when ((bufsize+1) % sizeof(int)) == 0
.
so example, if bufsize=10
, program behaves correctly, when bufsize=11
odd behaviour.
here sourcecode:
#include <stdio.h> #include <stdlib.h> #define bufsize 7 int max(int *buf); int main() { int bufsize = bufsize, *buf = malloc(sizeof(int[bufsize])); // read values int *ptr = buf; while(--bufsize + 1) { printf("input %d: ", bufsize - bufsize); scanf("%d", ptr); ++ptr; } // reset pointer , determine max ptr = buf; printf("\nmax: %d\n", max(ptr)); // cleanup free(buf); ptr = null; buf = null; exit(exit_success); } int max(int *buf) { int max = 0; while(*buf) { printf("%d\n", *buf); if(*buf > max) max = *buf; ++buf; } return max; }
and sample output bufsize=2 (correct) , bufsize=3 (incorrect).
suze:/home/born05/htdocs/experiments/c# gcc input.c && ./a.out input 1: 12 input 2: 23 12 23 max: 23 suze:/home/born05/htdocs/experiments/c# gcc input.c && ./a.out input 1: 12 input 2: 23 input 3: 34 12 23 34 135153 max: 135153
i have feeling extremely logical can't put finger on exact cause of misbehaviour. point out (perhaps obvious) flaw me?
it's pure luck works values of bufsize
. (in fact, me, breaks on bufsize=2
). here's why -- this:
while(*buf)
is not appropriate way check end of buffer. load value @ address pointed buf
, see if contents zero. since you're never explicitly putting 0 @ end of buffer, that's never going true, , loop run potentially forever, reading memory past end of buf
array , invoking undefined behavior.
you either need allocate element @ end of buf
array , set 0 (but program won't work right if user enters 0
input), or explicitly pass size of buf
max
function , use determine when should stop looping.
Comments
Post a Comment