2

Is there a tool like lint that can check potential endianness issue in a C code base? It's probably unrealistic for a tool to detect such problem during data sharing like network programming or file transfer. But checking that pointer casting abuse should not be that hard, right?

Basically, I'd like a tool to detect situation similar to the following code snippet.

#include <stdio.h>

void bar(char *cp)
{
    *cp = 'c';
}

void foo(int *intp)
{
    bar((char*)intp);
}


int main(void)
{
    int a = 0xAABBCCDD;

    foo(&a);

    printf("a = %d\n", a);

    return 0;
}

Any suggestion appreciated.

lang2
  • 11,433
  • 18
  • 83
  • 133
  • 2
    What tools did you try? I am not sure that pointer casting is related to endianness! Did you just try a recent GCC with all warnings e.g. `-Wall -Wextra`; and you might consider customizing GCC eg with http://gcc-melt.org/ – Basile Starynkevitch Apr 29 '12 at 17:24
  • 1
    Are there many situations where pointer-casting abuse is required other than for I/O? – Oliver Charlesworth Apr 29 '12 at 18:28
  • @BasileStarynkevitch for example, when you cast a int * to an char * and access the same memory through char *, you'd have endianness issue. Don't think those gcc flags will help here. – lang2 Apr 29 '12 at 18:54
  • I don't understand the endianness issue. How would `(int*)(char*)(void*)p` behave differently on big-endian vs little-endian? Endianness counts for casting a `struct {short s1, s2}` to an `int` – Basile Starynkevitch Apr 29 '12 at 19:01
  • 3
    @Basile: `int a = 0xAABBCCDD; char c = *(char *)&a;` will give different answers depending on system endianness; I think that's what the OP is referring to. – Oliver Charlesworth Apr 29 '12 at 19:13
  • You can [detect system endianness](http://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-a-c-program) in code and act accordingly. – Agnius Vasiliauskas Apr 30 '12 at 07:46
  • @0x69 I'm not trying to fix the problem. I'm trying to find a tool to detect such problem in the code. Thanks, – lang2 Apr 30 '12 at 13:02
  • So how hard is this test in the abstract? Look for a cast from one type to another type whose size is different. – Ira Baxter Jun 23 '12 at 04:13

0 Answers0