delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/05/27/10:26:13

From: james_oly AT wiltel DOT com (James Paul Oly)
Date: Fri, 27 May 94 08:53:05 -0500
To: Tom White <white AT moe DOT coe DOT uga DOT edu>
Subject: Re: Possible read() bug?
Cc: djgpp AT sun DOT soe DOT clarkson DOT edu
Reply-To: james_oly AT wiltel DOT com

> unsigned char buffer[50][2000];
> int length;
> 

> [...]
> 

> void ReadFile(void) {
>     int handle, i;
> 

>     handle = open("FILENAME.ABC", O_RDONLY | O_BINARY);
>     read(handle, &length, sizeof(int));
>     for(i=length; i>0; i--)
>         read(handle, buffer[i], 2000);
>     close(handle);
> }
> 

> Now if I call the function ReadFile without using buffer beforehand,
> everything works except that length gets completely clobbered.  gdb and
> exhaustive printfs tell me that length is clobbered only the first time
> through the loop in the read statement.

The first thing to do is rework the limits on your loop.  Your global  
declaration declares 50 "char[2000]"'s numbered buffer[0] through  
buffer[49].  The first time through the loop, i is 50 and you are reading  
into buffer[50], past the end of the array.  This is why length is being  
clobbered.

> 

> But if I first call some other stupid initalizing procedure like:
[....]

Why this happens, I have no idea.  Try changing the above to either
"for( i=length-1; i>=0; i--)" or "read(handle, buffer[i-1], 2000);" and  
see if this corrects the problem.

Jim
---
Jim Oly                                    E-Mail:  james_oly AT wiltel DOT com
(918) 561-6132                                         NeXTMail welcome!
Opinions expressed here do not necessarily reflect those of my employer.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019