473,836 Members | 1,407 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dealing with struct padding using a dynamic element

Problem:

I have a structure which needs to store its data in contiguous memory
by there is a dynamic element which can't be defined at compile time.
It needs to be aligned along a 4 byte boundary. This is what my
structure looks like:

START

struct tsBob
{
unsigned int fieldA;
unsigned int fieldB;

unsigned short varLen[0];
}

tsBob* myBob;

myBob = (tsBob*)malloc( sizeof(tsBob) + sizeof(unsigned short) * 1);

END

myBob needs an additional 3 bytes alloc'd to it to be aligned. I
don't want to use %

Finally the question,

Can I use a bitwise something to determine how many extra bytes I need
and malloc that with the
rest of the function call?
Oct 3 '08 #1
14 1831
mojumbo wrote:
Problem:

I have a structure which needs to store its data in contiguous memory
by there is a dynamic element which can't be defined at compile time.
It needs to be aligned along a 4 byte boundary. This is what my
structure looks like:

START

struct tsBob
{
unsigned int fieldA;
unsigned int fieldB;

unsigned short varLen[0];
I am not sure this is OK, you might consider giving it at least 1 element.
}
;
>
tsBob* myBob;

myBob = (tsBob*)malloc( sizeof(tsBob) + sizeof(unsigned short) * 1);
This is better accomplished by the correctly implemented 'operator new'
in the class itself, and then you just do

tsBob* myBob = new (true_varLen_co unt) myBob;
>
END

myBob needs an additional 3 bytes alloc'd to it to be aligned. I
don't want to use %
If the size in bytes is divisible by 4, it's going to be aligned on the
4 byte boundary. That's the specification of 'malloc', IIRC.
>
Finally the question,

Can I use a bitwise something to determine how many extra bytes I need
and malloc that with the
rest of the function call?
"Bitwise something"? Not sure what you mean. If you know how many
elements you need to give to your 'varLen' array, just do what you did,
but don't multiply the 'sizeof(unsigne d short)' by 1, multiply by the
required number of elements...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 3 '08 #2
On 2008-10-03 16:47, Victor Bazarov wrote:
mojumbo wrote:
>Problem:

I have a structure which needs to store its data in contiguous memory
by there is a dynamic element which can't be defined at compile time.
It needs to be aligned along a 4 byte boundary. This is what my
structure looks like:
Unless you can use some kind of struct/type which is 4 bytes (and make
sure that the first element in the array is correctly aligned using
padding) instead of the unsigned shorts you will have to take care when
allocating the memory. Perhaps using a factory-function (which allocates
the correct number of bytes) would be a good idea.
>struct tsBob
{
unsigned int fieldA;
unsigned int fieldB;

unsigned short varLen[0];

I am not sure this is OK, you might consider giving it at least 1 element.
It's not OK, the standard requires a number greater than zero, but some
compilers (gcc for one) accepts this. We use this a lot at work when
building messages to be sent over the network, and I find it helpful to
have the zero-sized array as a way of describing the message layout. It
usually looks something like this:

struct Msg
{
unsigned nrFoo;
unsigned nrBar;
#if 0
Foo foos[0];
Bar bars[0];
#endif
};

--
Erik Wikström
Oct 3 '08 #3
Thanks for the above comments but I will clarify:

I am using an overloaded operator new in the structure which takes the
number of elements just as you suggested, so the actual spec for the
struct does look like this.

struct tsBob
{
unsigned int fieldA;
unsigned int fieldB;

unsigned short varLen[0];

void* operator new(size_t, int aNum)
{ return malloc(sizeof(t sBob) + sizeof(unsigned short)*num; }
};

This is exactly what I'm trying to solve - aNum can come in as any
number (which is why I multiplied by one in my first explanation)

"bitwise something" meaning -
I also have another structure with float aFlts[0].
My new looks like this: void* operator new(size_t, int aNum) { return
sizeof(tsFltStr ) + sizeof(float)* aNum + (aNum & 0x01) ? 1:0); }

It's nice with 32-bits, just add another.
Also, I thought zero length arrays were part of the C99 standard?
Oct 3 '08 #4
mojumbo wrote:
[..]
Also, I thought zero length arrays were part of the C99 standard?
They may have been, but what relevance does it have here? We *are*
talking C++ here, aren't we? Not C99. Or are you unaware that they are
two different languages?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 3 '08 #5
On Oct 3, 4:47 pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
mojumbo wrote:
Problem:
I have a structure which needs to store its data in
contiguous memory by there is a dynamic element which can't
be defined at compile time. It needs to be aligned along a
4 byte boundary. This is what my structure looks like:
START
struct tsBob
{
unsigned int fieldA;
unsigned int fieldB;
unsigned short varLen[0];
I am not sure this is OK, you might consider giving it at
least 1 element.
It's not legal C++. Nor legal C, but in C, the last element may
have an incomplete array type, e.g.:
unsigned short varLen[] ;
You can, of course, give the final element a length of 1 in
either language, but then any array access with an index greater
than 0 is undefined behavior.
}
;
tsBob* myBob;
myBob = (tsBob*)malloc( sizeof(tsBob) + sizeof(unsigned short) * 1);
This is better accomplished by the correctly implemented
'operator new' in the class itself, and then you just do
tsBob* myBob = new (true_varLen_co unt) myBob;
If alignment isn't an issue (and I don't think it can be in his
exact case), then this should be accompanied with:

struct tsBob
{
unsigned short* varLen()
{
return reinterpret_cas t< unsigned short* >( this + 1 ) ;
}
} ;

or
struct tsBob
{
unsigned short& operator[]( std::size_t index ) ;
{
// bounds checking...
return reinterpret_cas t< unsigned short* >(
this + 1)[ index ] ;
}
} ;

for accessing the additional elements. I'd also do something to
ensure that the actual length was correctly memorized somewhere.
END
myBob needs an additional 3 bytes alloc'd to it to be aligned. I
don't want to use %
If the size in bytes is divisible by 4, it's going to be
aligned on the 4 byte boundary. That's the specification of
'malloc', IIRC.
No. All that malloc (or operator new()) guarantee is that the
returned pointer is sufficiently aligned for any type. In his
case, he's safe because it's not conceivable that unsigned short
require more alignment than the unsigned int in his struct. In
general, however, you do have to worry about alignment; the
implementation of std::basic_stri ng in g++ uses a similar trick,
and core dumps if you try to use std::basic_stri ng< double (or
probably std::basic_stri ng< long long >). (Hmmm. I wonder if
there are any platforms where wchar_t is equivalent to a long
long. If so, g++ has a real problem.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 4 '08 #6
James Kanze wrote:
>
No. All that malloc (or operator new()) guarantee is that the
returned pointer is sufficiently aligned for any type.
I knew about malloc, but are you sure this is true for operator new? It
should know the requirement of the needed type in advance so the largest
aligment seems like a overspecificati on?

-- Hrvoje Prge¹a
Oct 4 '08 #7
On 3 Oct, 22:25, Victor Bazarov <v.Abaza...@com Acast.netwrote:
mojumbo wrote:
[..]
Also, I thought zero length arrays were part of the C99 standard?

They may have been, but what relevance does it have here? *We *are*
talking C++ here, aren't we? *Not C99. *Or are you unaware that they are
two different languages?
Was it not the original intent of C++ to be compatible with C?

--
Max
Oct 4 '08 #8
Maxim Yegorushkin wrote:
>
Was it not the original intent of C++ to be compatible with C?
It still is, but the c++ standard is always catching up with the c
standard. Unspecified/flexible length arrays are from C99, the latest
c++ standard is C++03 (which is an updated version of c++98). It'll
probably get in the new standard, sometime in the future.

For more about incompatibiliti es see:
http://david.tribble.com/text/cdiffs.htm#C99-fam
http://en.wikipedia.org/wiki/Compati..._C_and_C%2B%2B
Oct 4 '08 #9
Hrvoje Prge¹a wrote:
James Kanze wrote:
>>
No. All that malloc (or operator new()) guarantee is that the
returned pointer is sufficiently aligned for any type.

I knew about malloc, but are you sure this is true for operator new? It
should know the requirement of the needed type in advance so the largest
aligment seems like a overspecificati on?
No, operator new does not know which type is being allocated, it is only
passed the size.

--
Ian Collins.
Oct 4 '08 #10

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

Similar topics

5
17673
by: Roy Hills | last post by:
When I'm reading from or writing to a network socket, I want to use a struct to represent the structured data, but must use an unsigned char buffer for the call to sendto() or recvfrom(). I have two questions: 1. Is it generally safe to "overlay" the structure on the buffer, e.g.: unsigned char buffer;
19
3089
by: Geetesh | last post by:
Recently i saw a code in which there was a structer defination similar as bellow: struct foo { int dummy1; int dummy2; int last }; In application the above array is always allocated at runtime using malloc.In this last member of the structer "int last" is not
20
2983
by: fix | last post by:
Hi all, I feel unclear about what my code is doing, although it works but I am not sure if there is any possible bug, please help me to verify it. This is a trie node (just similar to tree nodes) struct, I am storing an array of 27 pointers and a void pointer that can point to anything. typedef struct trieNode { struct trieNode *children; // The children nodes void *obj; // The object stored } TrieNode;
10
2437
by: Sean | last post by:
I have a struct that I wrote to test a protocol. The idea I had was to just declare the elements of the struct in the order in which they are sent and received as defined by the protocol. However, writing this struct to a file produces unexpected results. Here is a test struct I wrote: struct Tester { unsigned short first; unsigned int second;
10
3418
by: Mark A. Odell | last post by:
Is there a way to obtain the size of a struct element based only upon its offset within the struct? I seem unable to figure out a way to do this (short of comparing every element's offset with <offset>). What I would like to do is create an API something like this: #include <stddef.h> struct MemMap { unsigned char apple; // 8 bits on my platform
8
1684
by: Mike | last post by:
The following struct, DataStruct, is only part of a larger one that contains additional fields and arrays. I need the explicit layout because this struct is really a union, where some of the missing fields and arrays overlap. What's shown here, though, is sufficient for explaining the error. 290 bytes of data come from a serial device and is to be placed in this struct. Hence, I want this struct to be 290 bytes in size, and, if I'm...
5
4055
by: Hallvard B Furuseth | last post by:
Does struct assignment copy padding bytes? Some compilers do, but I couldn't find anything in the standard which says they must. What I need is for any padding bytes to contan initialized values before fwrite(), to shut up memory debuggers like Valgrind about writing uninitialized data to the file. Simplified code: static const struct S default_value = ...; struct S s, t;
8
4248
by: Chameleon | last post by:
I have a TGA image header struct. TGA has 18 bytes header, so the C struct too. why this return 20? sizeof(TGAHeader) I saw this in many structs. I believe compiler round up the size to 4 multiple.
3
3544
by: vikas talwar | last post by:
Hi All, Can you please explain me how the 'C' compiler allocate memory to 'struct'. Please go thu the example below and pls suggest me the solution for my problem. Here is my structure definition struct my_dev {
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10845
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
10254
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
9376
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
7792
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
6979
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
5650
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...
1
4456
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4019
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.