Search code examples
cmemorymemory-management

Register keyword: stack or heap


Some C memory management functions, such as malloc, store data into the heap instead of the (default) stack. The register keyword before a variable (e.g. register int n) specifies that n should be stored in a processor register. Does this correspond to the heap, stack, or none? In short, within the virtual memory space, where would a registered variable live?


Solution

  • C doesn't define where exactly a register variable has to be stored. It might end up as just a register but it could also be placed on the stack.

    From a C23 draft - §6.7.2 Storage-class specifiers:

    A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

    and:

    The implementation can treat any register declaration simply as an auto declaration. However, whether or not addressable storage is used, the address of any part of an object declared with storage-class specifier register cannot be computed [...].