Thread: Pointers, access violations and other things that go bump in the night...

  1. #1
    Registered /usr
    Join Date
    Aug 2001
    Location
    Newport, South Wales, UK
    Posts
    1,273

    Exclamation Pointers, access violations and other things that go bump in the night...

    Hi,

    I'm trying to make a simple RLE encoder that executes as fast as is possible. I've made this code:-
    Code:
    int EncodeFrame(FILE *src, FILE *dest)
    {
    	unsigned char *inptr, data;
    
    	fread(buffer, 65280, 1, src);
    	inptr = buffer;
    	while (inptr - buffer < 65280)
    	{
    		data = *(inptr++);
    		if (data == *inptr)
    		{
    			unsigned char count = 1;
    
    			while (data == *inptr && count < 63)
    			{
    				count++;
    				inptr++;
    			}
    
    			putc(0xC0 | count, dest);
    			putc(data, dest);
    		}
    		else
    		{
    			if (0xC0 == (data & 0xC0))
    				putc(0xC1, dest);
    			putc(data, dest);
    		}
    	}
    
    	printf("Done (%lu)\n", inptr - buffer);
    	return 0;
    }
    As you can see, it reads 65,280 bytes of data from an input file into a buffer of the same size, and uses inptr as a read pointer from which comparisons are made.

    The thing is, the printf message always manages to output "Done (65340)" instead of "Done (65280)", meaning that extraneous data is being stored, a problem highlighted by the decoder, which always ends up trying to write beyond the allocated memory area and crashing.

    Can anyone see what isn't right here?

  2. #2
    Unregistered
    Guest
    I am not sure that this is the problem, but I see that u can over shoot your 65280 boundary in the
    second (embedded) while loop. You need to break from that loop when you hit the max cond of the outer while. The inner while should look like

    Code:
    while (data == *inptr && count < 63)
                                                          {
                                                                  count++;
               inptr++;
    
              if (inptr == 25280) break;
       }
    Also add braces along with the if (good programming practice).

  3. #3
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    How about replacing the code
    Code:
                while (inptr - buffer < 65280)
    with
    Code:
                len = 0;
                while (len < 65280)
                ...
    ???

Popular pages Recent additions subscribe to a feed