Click here to Skip to main content
16,016,140 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In VC++, I have coded the structure variable in the program:

C#
typedef struct NetCfgPacket // 81 bytes
{
char    stx;
char    cmd;
char    mac[6];
char    wantype;
char    ip[4];
char    gateway[4];
char    netmask[4];
char    dns[4];
char    devicename[32];
char    modbusviewip[4];
short   modbusviewport;
char    telnet;
char    ssh;
char    ftp;
char    web;
char    lan;
char    bridge;
char    lanip[4];
char    lanmask[4];
char    wifi;
char    ports;
char    modeltype;
char    etx;
} RP_N ;


The sum of each length of these variables is 81 bytes. But, when I calculated the value of the sizeof(NetCfgPacket), this has length of 82 bytes.
Because of this difference between my expecting length and 'sizeof' function, it makes very serious problem to the communications of some socket programs.
Even though I do not check one byte one byte of the buffer made by above structure variable, the buffer size is the same size(= 82) of sizeof (NetCfgPacket).

1. I don't know what makes this difference.
2. Please let me know the solution of this.

Thank you

What I have tried:

After more one hour inspection, I found it.
Posted
Updated 29-Mar-16 1:24am
v3
Comments
nv3 29-Mar-16 6:32am    
So, I understand, you found the reason that causes this difference. Why don't you post a question then?

In case you have not found the reason yet: It is the implicit alignment that the compiler does, which causes this problem.
Patrice T 29-Mar-16 8:03am    
if question is solved, you should accept an answer to close the question.
you can even create you own answer and accept it.
Use Accept answer to close the question.

1 solution

This is sourced by the alignment of struct members. You can use the pack[^] pragma to ensure that there are no fill bytes in your structure:
C++
// Push current setting and pack to one byte boundary
 #pragma pack(push, 1)
typedef struct NetCfgPacket // 81 bytes
{
char stx;
// ...
} RP_N;
// Restore previous alignment
 #pragma pack(pop)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900