Skip to content

No warning about dangerous pointer casts #145218

Closed as not planned
Closed as not planned
@wo4mei3

Description

@wo4mei3

Both Clang and GCC do not issue any warnings about the following code, even with the -Wall option.
For Clang, I used Clang-16.
The executable produced by GCC caused a segmentation fault, while Clang's always prints 1.
By using the result of the cast, it becomes possible to access a struct member that was never actually allocated, and using it can easily cause a segmentation fault.
To avoid this, I propose that casting a pointer from a pointee type with a smaller size to one with a larger size should produce a compiler warning.

#include <stdio.h>

struct X {
        int x;
};

struct Y {
        int x;
        int y;
};

int main(void) {
        struct X x = {0};
        struct Y* y = (struct Y*) &x;
        y->y = 1;
        printf("%d", y->y);
        return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions