Hello,

Yes, an address is "aligned" when the numeric value of the address is a 
multiple of some value. In your case, the code is storing an int, which 
requires an alignment of 4 on most platforms. Most of the time, the compiler 
and library will automatically allocate things at suitable addresses for you so 
you don't have to worry about alignment. But, when you take an arbitrary char* 
value and cast it to int*, the C language says that it's your responsibility to 
make sure the pointer value is a multiple of the required alignment value (4, 
here).

Loading or storing with an address that is not suitably aligned for the type of 
the access triggers what the C language calls "undefined behavior". It may do 
what you expect sometimes, but C compilers sometimes find clever ways of 
optimizing using the assumption that all accesses are through aligned pointers. 
When they do this, it can cause the program to misbehave on unaligned pointers, 
so it's wise to avoid giving them the chance to cause trouble. It's the same 
situation under Emscripten, except that Emscripten *always* does something 
clever.

The typical way to fix this bug in your code is to use memcpy, since memcpy has 
no alignment requirement:

  memcpy(_bos, &val, sizeof(int));

Dan

----- Original Message -----
> Hi,
> 
> I was trying to assign an integer value to an array of unsigned char when I
> encountered an alignment error on SAFE_HEAP. The code is as follows:
> 
> *((int*)(_bos) = val;
> 
> where val is of type integer and _bos is of type unsigned char*. I am just
> curious as to why there is an alignment error when _bos is 1 byte in length
> and an integer is 4 bytes. Is it because the memory allocated to _bos is
> not big enough or not in multiples of 4?
> 
> --
> You received this message because you are subscribed to the Google Groups
> "emscripten-discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
> 

-- 
You received this message because you are subscribed to the Google Groups 
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to