Comment

Comment by eqvinox

No. [as in: this isn't about GCC.]

The C standard requires that pointers generally be created from referencing a valid, existing object. A misaligned integer is not a valid "object", thus the compiler may assume that all pointers to ints are aligned (to 4 bytes.)

https://en.cppreference.com/w/cpp/language/pointer

  Every value of pointer type is one of the following:
  
  - a pointer to an object or function (in which case the pointer is said to point to the object or function), or
  - a pointer past the end of an object, or
  - the null pointer value for that type, or
  - an invalid pointer value.
Relatedly, `malloc` is required to return a pointer with the largest alignment of any type ("suitably aligned to hold an object".)

Edit/Add: that's C++ in the link above, but it's the same in C. You can get a pointer from either a valid static/stack object, or malloc, which is "max" aligned. Either way it's required to point to a valid object, which includes correct alignment. If you implement your own memory management / allocator, it's also your responsibility to meet these same alignment requirements.

https://en.cppreference.com/w/c/language/object

parent eqvinox 6 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton