According to the rules, the cast is:

char* mem = (char*)malloc(sizeof(int)); int* numptr = (int*)mem; 

It leads to a strict align alignment violation, and this is an undefined behavior leading to Bus Error .

However, I have a memory block of, for example, 500 megabytes. Entirely composed of structures copied into it through memcpy POD, somewhere far away in another part of the galaxy (process).

I know all the indents. And simple, obvious access to read / write to the next structure looks like this:

 char* memory = (char*)malloc(real_big_size); ... //заполнение памяти MyType* MTptr = (MyType*)&memory[offset_for_current_mytype]; 

As described above, this method is prohibited by the rules of the language. The question is: how exactly should I read and work with the available memory, while not copying it (it is still 500Mb), and without disabling align alignment.

If writing & reading in such a seemingly simple and obvious case is prohibited by the rules of the language, maybe there is a way to get this kind of read-only access?

  • Do you write for any particular system (iron / os / compiler) or for all cases that you can think of? Specifically, look at alignments and if everything fits (usually malloc allocates memory with the most strict alignment) then follow the simple principle - "Do you need checkers or go?" - avp
  • @avp is a serialization code that works fine with all the optimizations on msvc-9.0 and gcc-4.12 (such are the build of the machine and this is just a given). But when migrating to Solaris CC - 5.12 it gives a Bus Error . Turning off align optimization can help, but lowers performance by 20–30% (calculations last for hours, and this is significant). Therefore, it is necessary to find another way of serialization / deserialization, which fits into the language standard. I am looking for him. - Arkady
  • @avp while, of course, would not want to do tens of thousands of memcpy(...) on all sorts of different structures, when a simple pointer would be enough to work with the block. - Arkady
  • You need to look specifically at your MyType structure. Apparently the reason is the alignment of its fields. As I understand it, msvc and gcc worked in x86 (in it, regardless of optimization, access to non-aligned fields is possible), but Solaris is probably SPARC (the hardware does not allow such freedom). In principle, you can immediately look at the packed attribute for the structure, but still, here you need to test everything thoroughly - avp
  • The structure on which the crash occurs now consists of unsigned int and 4 size_t . Can you tell me where to read about restricting access to the structure in SPARC related to my problem? - Arkady

0