Question about unions and heap allocated memory
- by Dennis Miller
I was trying to use a union to so I could update the fields in one thread and then read allfields in another thread. In the actual system, I have mutexes to make sure everything is safe. The problem is with fieldB, before I had to change it fieldB was declared like field A and C. However, due to a third party driver, fieldB must be alligned with page boundary. When I changed field B to be allocated with valloc, I run into problems.
Questions:
1) Is there a way to statically declare fieldB alligned on page boundary. Basically do the same thing as valloc, but on the stack?
2) Is it possible to do a union when field B, or any field is being allocated on the heap?. Not sure if that is even legal.
Here's a simple Test program I was experimenting with. This doesn't work unless you declare fieldB like field A and C, and make the obvious changes in the public methods.
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
class Test
{
public:
Test(void)
{
// field B must be alligned to page boundary
// Is there a way to do this on the stack???
this->field.fieldB = (unsigned char*) valloc(10);
};
//I know this is bad, this class is being treated like
//a global structure. Its self contained in another class.
unsigned char* PointerToFieldA(void)
{
return &this->field.fieldA[0];
}
unsigned char* PointerToFieldB(void)
{
return this->field.fieldB;
}
unsigned char* PointerToFieldC(void)
{
return &this->field.fieldC[0];
}
unsigned char* PointerToAllFields(void)
{
return &this->allFields[0];
}
private:
// Is this union possible with field B being
// allocated on the heap?
union
{
struct
{
unsigned char fieldA[10];
//This field has to be alligned to page boundary
//Is there way to be declared on the stack
unsigned char* fieldB;
unsigned char fieldC[10];
} field;
unsigned char allFields[30];
};
};
int main()
{
Test test;
strncpy((char*) test.PointerToFieldA(), "0123456789", 10);
strncpy((char*) test.PointerToFieldB(), "1234567890", 10);
strncpy((char*) test.PointerToFieldC(), "2345678901", 10);
char dummy[11];
dummy[10] = '\0';
strncpy(dummy, (char*) test.PointerToFieldA(), 10);
printf("%s\n", dummy);
strncpy(dummy, (char*) test.PointerToFieldB(), 10);
printf("%s\n", dummy);
strncpy(dummy, (char*) test.PointerToFieldC(), 10);
printf("%s\n", dummy);
char allFields[31];
allFields[30] = '\0';
strncpy(allFields, (char*) test.PointerToAllFields(), 30);
printf("%s\n", allFields);
return 0;
}