Beware, malloc returns an address that is aligned to 8 bytes. If your class just have a
char a[6];
member you are wasting 2 bytes (well if you have only 1 char or 1 bool you'll be wastin 7 bytes), while if you have a
v4si a;
vector of 4 bytes for SIMD instructions, you could have a wrong alignment wich require extra instructions to re-align it correctly.
Not wasting memory:
class TinyClass{
char c[3];
public:
TinyClass( char c1, char c2, char c3){
c[0] = c1; c[1] = c2; c[2] = c3;
}
};
Basically you have to create more than one object at a time (but they also must be destroyed at same time, so probably that's not suitable for you)
#include <new> //not needed if you already include any STL header
int number_of_items = 6;
void* a = malloc(sizeof(TinyClass)*number_of_items);
TinyClass * Ptr = reinterpret_cast< TinyClass* > (a);
for(int i=0; i<number_of_items; i++)
new(&Ptr[i]) TinyClass('a','b','c');
//later
for(int i=0; i<number_of_items; i++)
Ptr[i].~TinyClass(); //destructor
Ptr = NULL; // or Ptr = nullptr; if you have c++11
free(a);
.
Forcing alignement bigger than 8 bytes:
C++ possible implementation of aligned malloc
Of course forget what I said if you don't mind performance or memory waste ^^, because that's a bit bloat code.
Is that the same in C++? Not exactly, using "new" in c++ returns a pointer wich is at least aligned to what is needed, but there's no guarantee the implementation will not have a bigger alignement)