Hacker News new | ask | show | jobs
by khrbtxyz 1730 days ago
determine stack growth direction by having one function call another with a pointer to a local variable in the former and then compare that to a pointer to a local variable in the latter.

This is undefined behavior.

See n1570.pdf, Annex J page 560, J.2 Undefined behavior

Pointers that do not point to the same aggregate or union (nor just beyond the same array object) are compared using relational operators (6.5.8).

1 comments

Comparing the uintptr_t cast of two disparate pointers is not undefined behavior. A comparison may not yield a portable result because the integer representation of pointers may not be as plain memory addresses.

So such a simplistic stack growth detector may get the wrong answer, but it's not undefined behavior:

  char stack_grows_up(uintptr_t callers_local) {
    char my_local = (uintptr_t)&my_local > callers_local;
    return my_local;
  }
EDIT: Ah, and uintptr_t is an optional type. If the platform doesn't have it (e.g., because it's a segmented memory architecture) then this won't work, so it's not portable, but aside from that it's not undefined behavior, it's just that the computation of stack growth direction may well be wrong.