odd char * arithmetic in nginx binary

Maxim Dounin mdounin at mdounin.ru
Wed Oct 20 19:49:47 MSD 2010


Hello!

On Wed, Oct 20, 2010 at 04:31:27PM +0100, Hassan Syed wrote:

> I'm working on a authentication module and I need to produce a string
> without any inherent fixed structure, so I would just using ngx_sprintf and
> pointer arithmetic. However something insidious is going on during
> compilation. I have played arround with u_char * as well as char *'s. The
> gdb debug sessions goes as follows:
> 
> -----------------------------------------------------------------------------------------------------------------------
> 680    char * buf = (char *) ngx_palloc( r->pool, sz);
> (gdb) n
> 681    if ( buf  == NULL)
> (gdb) n
> 687    if( parameter_count > 0) {
> (gdb) n
> 688        buf = (char *) ngx_sprintf((u_char *)buf,"%V?", &
> alcf->redirect_url);
> (gdb) n
> 690        buf++; buf++;// buf++; buf++; buf++;
> (gdb) p buf
> $1 = 0x6d2de0 "lala?"
> (gdb) n
> 698        if( parameters[i]->len != 0) {
> (gdb) p buf
> $2 = 0x6d2de7 ""
> -----------------------------------------------------------------------------------------------------------------------
> 
> I should see 2 = 0x6d2de2 "la?"  as output
> 
> I have only incremented the char pointer twice, yet the pointer moves
> forward 7 bytes (and when I do a +=5 it moves forward 10 bytes). I am hoping
> someone can tell me what is going on here, as t his has
> completely flabbergasted me.

Most likely you are facing compiler optimization here.  It just 
don't load new value into buf variable until it's done all 
calculations.  Try -O0.

Note well: ngx_sprintf() returns pointer to character after last 
one it printed, so you aren't expected to see any of ngx_sprintf() 
output in "p buf".

Maxim Dounin



More information about the nginx-devel mailing list