<< Back to previous view

[PCC-355] pointer arithmetic gives wrong result Created: 11/Jun/11  Updated: 07/Jul/11

Status: Resolved
Project: pcc
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Minor
Reporter: Iain Hibbert Assignee: Anders Magnusson
Resolution: Fixed Votes: 0
Environment: NetBSD/i386

An equivalent construct to the following code was being used to rebase a list of pointers,
where the actual data was in a separate buffer which had been realloc()ed.

#include <stdio.h>

struct hdr {
    int length;
    int offset;

struct hdr *new = (struct hdr *)0xbb300000;
struct hdr *old = (struct hdr *)0xbb700000;

main(int ac, char *av[])
    struct hdr *p, *q;

     * this value is naturally aligned
    p = (struct hdr *)0xbb7fff78,
    q = p - old + new;
    printf("1. %p -> %p\n", p, q);

     * this value is not
    p = (struct hdr *)0xbb7fff34;
    q = p - old + new;
    printf("2. %p -> %p\n", p, q);

    return 0;

so, as the pointers are all known to be greater than the old buffer start, the
new value is calculated by subtracting the old buffer start, then adding in the
new one.

When compiled with pcc and run, this program prints the following

1. 0xbb7fff78 -> 0xbb3fff78
2. 0xbb7fff34 -> 0xbb3fff30

but the second value is wrong.. it should be "0xbb3fff34" which seems to be
caused by the value not being naturally aligned to an exact number of structures..

Comment by Anders Magnusson [ 01/Jul/11 05:32 PM ]
This isn't a bug since C99 states that pointer arithmetic is only allowed on elements from the same object.
But, since this may give people unexpected results I change it to a low-priority change request to add this functionality.
Comment by Anders Magnusson [ 07/Jul/11 09:53 AM ]
Now added. It was quite simple to fix this.
Generated at Tue Oct 17 16:59:30 CEST 2017 using JIRA Enterprise Edition, Version: 3.13.1-#333.