C & C++

C & C++

Made by DeepSource

Risky cast after possibly misaligned pointer offset CXX-S1014

Security
Major

Pointer offset(or any other arithmetic operation) on a pointer casted to a different type (than its original type) is risky and can result in undefined behaviour. The reason for such behaviour is that the memory alignment may change for types on every targeted platform.

Bad practice

void foo() {
    int i[2] = {10, 20};
    // The following code will not work on platforms
    //  where width of `int` may not be `4` `char`(s)
    int j = *(int*)((char*)i + 4);
}

Recommended

void foo() {
    int i[2] = {10, 20};
    // Following will work irrespective of the
    // platform defined size of int
    int j = *(int*)(i + 1);
}