NO

Author Topic: Pointer arithmetic bug  (Read 2559 times)

kolo32

  • Guest
Pointer arithmetic bug
« on: September 08, 2011, 10:55:22 AM »
Code: [Select]
#include <stdio.h>

int main(void)
{
char * p = "bugfix";
p += 4;
p--;
puts(p);
return 0;
}

This program under Pelles C 6.50.8 RC #4 prints an empty line :( Expected result: "fix" must be printed.

After changing to:
Code: [Select]
static const char * p = "bugfix";

it works as expected.

Offline AlexN

  • Global Moderator
  • Member
  • *****
  • Posts: 394
    • Alex's Link Sammlung
Re: Pointer arithmetic bug
« Reply #1 on: September 08, 2011, 12:30:44 PM »
Ro much optimized by the compiler. If it stores the string as locale string, it seems to optimize the storage for the string. So there is only "ix" on the stack and p points to the not initialized character before the 'i', which is in this case a 0x00, and the output for this is an empty line.
best regards
 Alex ;)

MichaelT

  • Guest
Re: Pointer arithmetic bug
« Reply #2 on: September 09, 2011, 10:06:55 AM »
Edit:

I decided to retract my statement earlier.

This because I investigated the issue further and you're quite right.
It seems the optimization is premature.


« Last Edit: September 09, 2011, 11:26:20 AM by MichaelT »