On Sat, Oct 09, 2010 at 06:36:55PM +0200, merlyn wrote:
> Hi all,
> 
> I'm facing really weird behavior of simple C program
> running under OpenBSD (4.7 and CURRENT).
> 
> The code follows. The output also. The file to test the program with
> is also inline attached.
> 
> The decomp procedure reads input, writes it to the stdout. All 4-chars
> preceeded by number are printer number times (e.g. 4abcd ->
> abcdabcdabcdabcd).
> 
> ./a.c < test_file.txt
> should have output
> aaaaa bb
> ccccccccccc      dddd
> 
> however it sometimes ( 1 from 3 tryies, sometimes 1 from 20 or even 1
> from 40)
> 
> looks like
> aaaaa bb
> ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
> cccccccccccccccccccccccccccccccccccccc
> dddd
> 
> 
> I've tryied this code with OpenBSD 4.7, OpenBSD CURRENT, CentOS Linux,
> FreeBSD 8.0 (all i386 arch), but the problem occurs only at OpenBSD (both
> versions).
> 
> Does anyone know please where could be the problem? Because I have
> really no idea.
> 
> Thanks a lot,
> Milan Bartos
> 
> 
> 
> ---- CODE ---
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> void decomp(unsigned int N){
>       char *pole;
>       pole=malloc( sizeof(char) * N );
>     char character;
>     int i,j;
>     int counter;
>     while( (character = getchar()) != EOF){

getchar() returns 'int' not 'char'. isdigit() and putchar() take
'int' not 'char'.

>         if( isdigit(character) ){
>             counter=atoi(&character);

atoi() takes a pointer to a string, not a pointer to a single
characer. Results will depend on the 'random' stack garbage in the
following variables i and j. Or possibly the random stack garbage
of any alignment gaps on the stack. 'int i = 0, j;' may make it
work predictably but is the wrong answer.


>                       for( i=0 ; i < N ; i++){
>                               pole[i]=getchar();
>                       }

Checking for EOF here is probably a good idea. Never trust input. :-).

>                       for( i=0 ; i < counter ; i++){
>                               for( j=0 ; j < N ; j++){
>                                       putchar(pole[j]);
>                               }
>                       }
> 
>         }
>         else {
>             putchar(character);

putchar() can fail, so checking that for EOF is also good, paranoid practice.

.... Ken

Reply via email to