Re: One struct pointer question



On 7 May 2005 14:34:11 -0700, "QQ" <junciu@xxxxxxxxx> wrote:

>Here is my program
>the head is
>typedef struct struct_CN
>{
> unsigned char magicA;
> unsigned char magicB;
> unsigned short msgLen;
>} CN;
>
>
>typedef struct struct_CcDev
>{
> CN Header;
> unsigned short action;
>} CcDev;
>
>CcDev CcDev_packet;
>
>Evaluate_CN(CN *CN_p)
>{
>
> strcpy(&CN_p->magicA,"A");

magicA has room for a single character. You are attempting to copy
two characters into it. The only reason this does not lead to
undefined behavior is that the next byte in memory is guaranteed to
belong to your structure.

> printf("magicA is %s\n", &CN_p->magicA);
> strcpy(&CN_p->magicB,"H");

Same for magicB.

> printf("magicB is %s\n", &CN_p->magicB);
> CN_p->msgLen = 1234;
> printf("msgLen is %d\n", &CN_p->msgLen);
>}
>void Evaluate_CcDevRegMsg()
>{
> Evaluate_CN(&CcDev_packet.msgHeader);
> printf("CcDev_packet.CN.magicA = %s\n",&CcDev_packet.Header.magicA);

magicA need not be the address of a valid string. If we assume that
the structure has no padding (reasonable if sizeof(short) is 2), then:
The first strcpy put the 'A' in magicA and a '\0' in magicB.
The second put the 'H' in magicB and the '\0' in the first byte of
msglen.
The integer assignment put 0x04d2 into msglen (in either order).

Where is the '\0' that will terminate the string that starts with 'A'?

> printf("CcDev_packet.CN.magicB = %s\n",&CcDev_packet.Header.magicB);

Ditto.

> printf("CcDev_packet.CN.msgLen = %d\n",&CcDev_packet.Header.msgLen);

%d requires an int. You are passing it an int*. This leads to
undefined behavior. You probably did not intend to have the & there.

>}
>
>
>When I use gcc to compile
>gcc file.c
>
>I got the output as
>magicA is A
>magicB is H
>msgLen = 1234
>CcDev_packet.CN.magicA = AH?
>CcDev_packet.CN.magicB = H?
>CcDev_packet.CN.msgLen = 134519298
>
>
>Is there anything wrong with it?

Of course.

>
>Thanks a lot!



<<Remove the del for email>>
.



Relevant Pages