Segmentation Fault When Casting Between Structs with Incompatible Fields in C
I'm dealing with I've searched everywhere and can't find a clear answer. I'm encountering a segmentation fault in my C program while trying to cast between two structs that have incompatible fields. I have two struct definitions, `Person` and `Employee`, where `Employee` is supposed to extend `Person` with an additional field for salary. However, when I try to cast a pointer to `Person` to a pointer to `Employee`, I get a segmentation fault when accessing the salary field. Here are the relevant struct definitions: ```c typedef struct { char name[50]; int age; } Person; typedef struct { Person base; float salary; } Employee; ``` I have a function where I initialize a `Person` and then try to use it as an `Employee`: ```c void processEmployee(Person *p) { Employee *e = (Employee *) p; // Unsafe cast printf("Employee salary: %.2f\n", e->salary); } int main() { Person p = {"John Doe", 30}; processEmployee(&p); return 0; } ``` Running this code gives me the following output: ``` Segmentation fault (core dumped) ``` I know that the memory layout for `Person` and `Employee` is different, but I thought casting the pointer would work fine as long as I donβt access the additional fields directly. I've tried adding checks to ensure that the pointer is not NULL before accessing it, but it still crashes. What am I missing here? Is there a proper way to handle polymorphism in C without running into segmentation faults? Is there a better approach? I'm working on a web app that needs to handle this. I'd really appreciate any guidance on this. This is happening in both development and production on Windows 10. I'd be grateful for any help.