0

I'm aware of this SO question and this SO question. The element of novelty in this one is in its focus on Xcode, and in its use of square brackets to dereference a pointer to void.

The following program compiles with no warning in Xcode 4.5.2, compiles with a warning on GCC 4.2 and, even though I don't have Visual Studio right now, I remember that it would consider this a compiler error, and MSDN and Internet agree.

#include <stdio.h>

int main(int argc, const char * argv[])
{
    int x = 24;

    void *xPtr = &x;
    int *xPtr2 = (int *)&xPtr[1];

    printf("%p %p\n", xPtr, xPtr2);
}

If I change the third line of the body of main to:

int *xPtr2 = (int *)(xPtr + 1);

It compiles with no warnings on both GCC and Xcode.

I would like to know how can I turn this silence into warnings or errors, on GDB and especially Xcode/LLVM, including the fact that function main is int but does not explicitly return any value (By the way I think -Wall does the trick on GDB).

Community
  • 1
  • 1
damix911
  • 4,165
  • 1
  • 29
  • 44
  • xptr[1] !!! how?? xPtr is pointer to a void. not a 2D array. – Anoop Vaidya Jan 04 '13 at 18:43
  • @Anoop Vaidya: I know it's wrong, Xcode doesn't and this troubles me. And yeah, it's not a 2D array, but maybe you meant "two-element array". I think that Visual Studio would have issued an error even if I wrote xPtr[0] though, and I think that is totally awesome. – damix911 Jan 04 '13 at 18:49
  • because it isnt wrong.. the compiler doesnt know how big the pointer is ... a void[] ~~ void* – Daij-Djan Jan 04 '13 at 19:48

1 Answers1

0

that isnt wrong at all...

the compiler doesnt know how big the pointer is ... a void[] ~~ void*
thats why char* used as strings need to be \0-terminated

you cannot turn on a warning for that as it isnt possible to determine a 'size of memory pointer to by a pointer' at compile time

void *v = nil;
*v[1] = 0 //invalid

void *v = malloc(sizeof(int)*2);
*v[1] = 0 //valid

*note typed inline on SO -- sorry for any non-working code

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • thank you for your answer. I feel like the compiler always knows how big a pointer is, and I believe it is 4 or 8 bytes in most modern architectures. What it does not know is the size of the pointed area, but this is not an issue at compile time; your answer seem to focus on this aspect, as you show a call to malloc to allocate the required space. I think also Anoop Vaidya mentioned this size in a way; an issue at compile time arise when the pointed type is incomplete or is void, because the compiler is given no size information, and no machine code can be generated. – damix911 Jan 05 '13 at 01:07