473,785 Members | 2,863 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mapping a struct to a memory block....

I have a multi-field struct and a memory block (created using malloc) that
contains structured data. If I map the struct to the memory block, am I
guaranteed that the struct fields will be filled properly or do I have to
worry about the compiler padding the struct?

Example:

typedef struct
{
int16 field1; // 2 bytes
int32 field2; // 4 bytes
} st;

// memblock contains exactly 6 bytes
st* var = (st*) memblock;

Apr 20 '07 #1
14 8847
barcaroller wrote:
I have a multi-field struct and a memory block (created using malloc) that
contains structured data. If I map the struct to the memory block, am I
guaranteed that the struct fields will be filled properly or do I have to
worry about the compiler padding the struct?

Example:

typedef struct
{
int16 field1; // 2 bytes
int32 field2; // 4 bytes
} st;

// memblock contains exactly 6 bytes
st* var = (st*) memblock;
On many systems, sizeof(struct st) will be 8 due to alignment padding.
Alignment and padding aren't standardised, so doing what you propose is
not a good idea.

--
Ian Collins.
Apr 20 '07 #2
"barcarolle r" <ba*********@mu sic.netwrites:
I have a multi-field struct and a memory block (created using malloc) that
contains structured data. If I map the struct to the memory block, am I
guaranteed that the struct fields will be filled properly or do I have to
worry about the compiler padding the struct?
Compilers are allowed to insert padding between structure members
or after the end of a structure. The C language doesn't provide
a way to prevent or control this (although your implementation
might).
typedef struct
{
int16 field1; // 2 bytes
int32 field2; // 4 bytes
} st;
The standard type names for these types would be int16_t and
int32_t, declared in <stdint.hin C99 implementations that
support them.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Apr 20 '07 #3
"barcarolle r" <ba*********@mu sic.netwrites:
I have a multi-field struct and a memory block (created using malloc) that
contains structured data. If I map the struct to the memory block, am I
guaranteed that the struct fields will be filled properly or do I have to
worry about the compiler padding the struct?
[...]

You have to worry about the compiler padding the struct.

See question 2.12 in the comp.lang.c FAQ, <http://www.c-faq.com/>.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 20 '07 #4

"Ian Collins" <ia******@hotma il.comwrote in message
news:58******** ******@mid.indi vidual.net...
On many systems, sizeof(struct st) will be 8 due to alignment padding.
Alignment and padding aren't standardised, so doing what you propose is
not a good idea.
Does this also apply to reading/writing a file? I have seen code where
structs are being written to and read from files. If the compiler is
allowed to use padding then neither the writes nor the reads are safe.
Apr 21 '07 #5
barcaroller wrote:
"Ian Collins" <ia******@hotma il.comwrote in message
news:58******** ******@mid.indi vidual.net...
>>On many systems, sizeof(struct st) will be 8 due to alignment padding.
Alignment and padding aren't standardised, so doing what you propose is
not a good idea.


Does this also apply to reading/writing a file? I have seen code where
structs are being written to and read from files. If the compiler is
allowed to use padding then neither the writes nor the reads are safe.

They are assuming the same compiler on the same system is being used to
generate the code that reads and writes the struct.

--
Ian Collins.
Apr 21 '07 #6

"Ian Collins" <ia******@hotma il.comwrote in message
news:58******** ******@mid.indi vidual.net...
They are assuming the same compiler on the same system is being used to
generate the code that reads and writes the struct.
If I understood you correctly, you are saying that if the compiler uses
padding, it will do so in a consistent manner. Hence, if I use a struct to
write data into a memory buffer, then I am safe to read the data as long as
I use exactly the same struct (even if I read from a memory buffer that was
copied from the original memory buffer using memcpy).
Apr 21 '07 #7
barcaroller wrote:
"Ian Collins" <ia******@hotma il.comwrote in message
news:58******** ******@mid.indi vidual.net...
>>They are assuming the same compiler on the same system is being used to
generate the code that reads and writes the struct.


If I understood you correctly, you are saying that if the compiler uses
padding, it will do so in a consistent manner. Hence, if I use a struct to
write data into a memory buffer, then I am safe to read the data as long as
I use exactly the same struct (even if I read from a memory buffer that was
copied from the original memory buffer using memcpy).
Probably. I've never seen a case where this isn't true, but you never know!

--
Ian Collins.
Apr 21 '07 #8
"barcarolle r" <ba*********@mu sic.netwrites:
"Ian Collins" <ia******@hotma il.comwrote in message
news:58******** ******@mid.indi vidual.net...
>They are assuming the same compiler on the same system is being used to
generate the code that reads and writes the struct.

If I understood you correctly, you are saying that if the compiler uses
padding, it will do so in a consistent manner.
Strictly speaking, I think that's only required within a single
execution of a program, but practically speaking you can pretty much
depend on binary files being compatible as long as the same compiler
was used to compile the code that writes them and the code that reads
them. (But some compilers may provide command-line options that
affect layout.)

It's likely, but by no means guaranteed, that layouts will be
consistent across different compilers on the same system. Compiler
vendors are motivated to make things easy for their users.

Across different platforms, though, all bets are off unless you use
text-based formats.
Hence, if I use a struct to
write data into a memory buffer, then I am safe to read the data as long as
I use exactly the same struct (even if I read from a memory buffer that was
copied from the original memory buffer using memcpy).
Yes.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 21 '07 #9
On Fri, 20 Apr 2007 20:10:53 -0400, in comp.lang.c , "barcarolle r"
<ba*********@mu sic.netwrote:
>
"Ian Collins" <ia******@hotma il.comwrote in message
news:58******* *******@mid.ind ividual.net...
>On many systems, sizeof(struct st) will be 8 due to alignment padding.
Alignment and padding aren't standardised, so doing what you propose is
not a good idea.

Does this also apply to reading/writing a file? I have seen code where
structs are being written to and read from files. If the compiler is
allowed to use padding then neither the writes nor the reads are safe.
Its safe provided both reads and writes are being performed by the
same version of the same software on the same hardware, compiled by
the same compiler...

People make good money writing tools to convert binary data of this
sort between versions, platforms and applications.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Apr 21 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
3006
by: Alfonso Morra | last post by:
Hi, I am at the end of my tether now - after spending several days trying to figure how to do this. I have finally written a simple "proof of concept" program to test serializing a structure containing pointers into a "flattened" bit stream. Here is my code (it dosen't work - compiles fine, pack appears to work, but unpack retrieves jibberish and causes program to crash).
7
7203
by: Zero | last post by:
If we have a structure like: struct something{ int *a; int b; }; We allocate mempry for a using malloc or calloc. The question is when we want to know the size of the structure, sizeof(struct something), it will not give us the correct number (i.e. the size of the structure
3
1636
by: Nadav | last post by:
Hi I wonder... Is it possible to define the address to which shared memory will be mapped In other words is it possible to apriory define the address MapViewOfFile returns Dlls are being loaded and relocated on the relocation table during Process Creation, is it possible to use/manipulate this mechanism somehow... Nadav.
11
4718
by: redefined.horizons | last post by:
First, I would thank all of those that took the time to answer my question about creating an array based on a numeric value stored in a variable. I realize after reading the responses and doing some more research, that what I really need is known in C as a "dynamic array". Basically, you surpass the array notation and use pointers with memory obtained with malloc() or calloc(). I think this will do just what I needed. That has brought...
1
2593
by: Vikas | last post by:
Hi I have been browsing C struct to C# mapping emails on the newsgroups, but I haven't been able to find a solution to my problem. My C structure looks like this: struct myCstruct { char * data; size_t size; };
8
3994
by: barcaroller | last post by:
I have a pointer to a memory block. Is there a way I can map a vector<Tto this memory block? I would like to take advantage of the powerful vector<T> member functions. Please note that I cannot copy the data into the vector because the memory block is used/read by other objects.
3
2977
by: dreiko466 | last post by:
(sorry about my english...) I am a newbie in C (3 month expierience) I have wrote a simple test programm in VS2005, what i do wrong?Please... In this programm i create a double linked list.Then pass its first block pointer inside the structure Array to Array ->first and the last block pointer inside the structure Array to Array ->last.So i can manipulate the double linked list as a dynamic array. The cells of this dynamic array are...
4
9816
by: hugo.arregui | last post by:
Hi! I have two struts like that: struct { int num; int num2; struct b arrayOfB; } a;
5
5237
by: michelqa | last post by:
Hi, I need to call a lot of different native SendMessage to retreive informations from non managed application. Some win32 messages use struct pointer for lparam....how to create and marshaling the struct to be able to use it in sendmessage... Here is an example LM_GETITEM: http://msdn.microsoft.com/en-us/library/bb760720(VS.85).aspx
0
10329
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10152
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8974
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.