TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Bill Birrell
from: Darin McBride
date: 2004-04-22 18:06:52
subject: Squares

Hello Bill!

Replying to a message of Bill Birrell to Darin McBride:

 >> The while statement will always increment s such that
 >> it points to the character after the nul, which means
 >> it's pointing to space that's either unallocated (the
 >> one byte after allocated memory is allowed to be
 >> pointed at, but not dereferenced, unlike the byte
 >> before allocated memory), or at least garbage.

 BB>     Dispute!

 BB>     What you say is true with pre-increment, but with post-increment
 BB> it evaluates *s and finds it false before it increments s past the
 BB> nul byte. Since the falsity terminates the loop, the incremented

Um, no.  ;-)

#include 

int main()
{
    char* str = "blah\0X";
    char* s = str;

    while (*s++) {
        printf("at [%c] \n",*s,*s);
    }
    printf("\ns => [%c] \n",*s,*s);
    if (*s != '\0') {
        printf("Looky here! s was incremented too far!\n");
    }

    return 0;
}

[0] d:\tmp\a>gcc foo.c -o foo.exe

[0] d:\tmp\a>foo
at [l] 
at [a] 
at [h] 
at [ ] 

s => [X] 
Looky here! s was incremented too far!

Pretty much sums it up.  Not only does s never point to the first
character, it ends up pointing past the end.  Bad, bad, bad.  ;-)

Regardless, post-increment still increments the pointer *prior* to
evaluating the if statement using the *old* value of s.

if (*s++) looks like:

: dereference s, push on stack.
: increment s
: test item on stack

Actually, due to the atomic nature of the increment, it is supposed to look
as close to this as possible:

: dereference s, push on stack, increment s
: test item on stack

Not all processors (if any?) allow this in an atomic action.  But it should
look like this as much as possible (in other words, in a multi-threaded
app, s could change between the dereference and the increment).

 BB> pointer is not dereferenced by the loop. That would not occur until
 BB> the next iteration. It is permissible to point past the end, but not
 BB> to dereference it once there.

The last statement is what I said ;-)

 BB>     As you say, habit. Both methods have their merits. This is the
 BB> merit of post-increment.

You may want to rethink your merits ;->

Darin

---
* Origin: Tanktalus' Tower BBS (1:250/102)
SEEN-BY: 633/267 270
@PATH: 250/102 99 10/345 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.