-1

I'm not sure why this is happening, I think I'm doing everything correctly.. Maybe someone can help point me in the right direction.

    unsigned short* x;

    int textLeft[16];

    x = shm->textLeft;

These are spaced out in the program so I didn't want to copy a bunch of code but if more is needed please let me know.

Shouldn't this work correctly without giving me the incompatible pointer type?

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
user2318083
  • 567
  • 1
  • 8
  • 27
  • 2
    What is shm? How is it defined? if it is `int textLeft[16]`, then it's normal, `unsigned short*` is NOT the same as `signed int[]` – Eregrith Dec 19 '13 at 11:04

3 Answers3

2

No, this should not work, because you're assigning an int* value to an unsigned short* variable, which causes undefined behavior per the C strict aliasing rule.

The way to make this work without changing the types is to

  1. cast the pointer, x = (unsigned short *)(shm->textLeft);, and
  2. compile with GCC's -fno-strict-aliasing to turn the aliasing rule off.

But really, I strongly recommend you change the types to be compatible, since otherwise you're tying yourself to a single compiler's extensions to the C standard.

Community
  • 1
  • 1
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • +1 In C, type errors doesn't really exist, it's just that you haven't cast things enough. –  Dec 19 '13 at 11:17
  • 1
    @HermanTorjussen: type errors do exist; without the `-fno-strict-aliasing` (a GCC-specific option), the compiler is free to break this code in any way it pleases. – Fred Foo Dec 19 '13 at 11:19
  • And that was my attempt at humour.. My point was that C is not very strict with types. –  Dec 19 '13 at 11:20
  • 1
    @larsmans: You should have added: "*Don't try this at home!*" ...;-) – alk Dec 19 '13 at 11:21
  • 2
    @HermanTorjussen: apologies, irony doesn't always pass through the internet unscathed. – Fred Foo Dec 19 '13 at 11:21
  • This works, now I got an "Invalid Argument" error, I think it's because I need to clear the shared memory. Hopefully that's the reason. – user2318083 Dec 19 '13 at 11:26
1
`unsigned short`

is not

`int`

So define

  • x as int * or
  • textLeft[16] as unsigned short

and things are ok.

alk
  • 69,737
  • 10
  • 105
  • 255
  • You're right, I thought I had did that before but it took care of the error. But I remember now I get another error from something else. I get an "Invalid Argument" when before doing int it didn't have that. – user2318083 Dec 19 '13 at 11:15
1

In your case x is a unsigned short pointer and textLeft is a signed integer. You are trying to assign signed integer address to unsigned short pointer.

Chinna
  • 3,930
  • 4
  • 25
  • 55