In a previous question I asked related to bitwise operations I was told that a code that accesses to a char array with an int pointer (to operate on bigger chunks of bytes at a time) may be problematic if the char array is not aligned with a int address.
Then, thinking in C, I wondered what goes on when malloc allocates memory for an unknown type. For example, if I do void *p = malloc(sizeof(int));, do I get a valid char/int/long-aligned memory address?
According to some answers here in SO that cite the standard, "the pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type".
Thus, I understand that I can go from char* to int* with no problems in this case:
char *p = malloc(16);
int *n = (int*)p; // use n a base of an array of 16 / sizeof(int) ints
Is it correct?
Moving to C++, it seems that the same rule appears in the standard. Then, can I assume that there are not alignment risks if I do this?
char *p = new char[16];
int *n = reinterpret_cast<int*>(p);