I got a segmentation fault when invoked a function immediately following a pointer assignment.
typedef struct
{
DMINT field1;
DMINT field2;
DMINT field3;
} MSG1;
typedef struct
{
....
} MSG;
/* MSG is size of 1040 byte, bigger than MSG1 in size */
int main()
{
MSG Msg;
MSG1 *pMsg1;
int mid;
pthread_t tid;
...
Recv_msg( mid, &Msg); /* this function does a memcpy to &Msg */
pMsg1 = (MSG1 *)&Msg;
//ret = pthread_join(pMsg1->..... ); /* Got Segmentation fault here by GDB*/
/* even the first argument has nothing to do with pMsg1, SEGV is still received */
ret = pthread_creat(&tid, NULL, thread_function, NULL); /* Got Segmentation fault here by GDB*/
It works fine if I remove pMsg1 = (MSG1 *)&Msg.
Is it because the two pointers have different sizes?
You can safely convert one struct pointer to another only if one struct lays in the beginning of another (no matter sizes they are, see C std.):
Otherwise you could get into aligning issues and undefined behavior.