Search code examples
cfunctionpointersundefined-behavior

Is "static int* foo()", in C, a static function returning a pointer, or a function returning a static pointer?


I'm working with an Arduino library I slightly modified for AVR C, which interfaces with an ICM-20948 IMU (Integrated Measurement Unit). In it, I found this "gem":

uint8_t* temp = read_multiple_icm20948_reg(ub_0, B0_TEMP_OUT_H, 2);

Where read_multiple... is defined as:

static uint8_t* read_multiple...(userbank ub, uint8_t reg, uint8_t len){
    static uint8_t reg_val[6];
    .
    .
    .
    return reg_val;
}

My question is, is this a static function that returns a pointer, or a regular function that returns a static pointer? And should I restructure it to look like this:

uint8_t* temp;
read_multiple_icm20948_reg(temp, ub_0, B0_TEMP_OUT_H, 2);

Where read_multiple... would be defined as

void read_multiple...(uint8_t *ret, userbank ub, uint8_t reg, uint8_t len);

To avoid undefined behaviour in the form of returning a pointer to stack-allocated memory.


Solution

  • Turned my comments into an answer, as requested:

    1. The function static int* foo() { /* ... */ } (as well as read_multiple... or any similar function) is a static function returning a pointer.
      There is no such thing as a "static pointer" in this context.
    2. It's OK to return reg_val in the function read_multiple....
      This is because reg_val is static, which means that it is not on the stack. Therefore it's OK to return its address in the form of a pointer to it.
      Your last sentence: "To avoid undefined behaviour in the form of returning a pointer to stack-allocated memory" should therefore not be a concern.