memoryarduinodynamic-memory-allocationstatic-memory-allocation

return byte array with Arduino


I have an array that contains bytes of information (a payload), but I want to use this array in two functions. How can I return it? I don't know if I have to declare it different or in other place.

My code:

void loop() {
    byte payload[] = find_fix();
    delay(5*60000);
}


byte find_fix(){
    byte payload[9];

    double lati = sodaq_gps.getLat();
    double longi = sodaq_gps.getLon();
    int nsatis = sodaq_gps.getNumberOfSatellites();
    long lax = lati * 10000000;
    long lox = longi * 10000000;

    payload[0] = (byte) ((lax & 0xFF000000) >> 24 );
    payload[1] = (byte) ((lax & 0x00FF0000) >> 16 );
    payload[2] = (byte) ((lax & 0x0000FF00) >> 8 );
    payload[3] = (byte) ((lax & 0X000000FF));
    payload[4] = (byte) ((lox & 0xFF000000) >> 24 );
    payload[5] = (byte) ((lox & 0x00FF0000) >> 16 );
    payload[6] = (byte) ((lox & 0x0000FF00) >> 8 );
    payload[7] = (byte) ((lox & 0X000000FF));
    payload[8] = (byte) (nsatis);
    SerialUSB.print(" MIGUEL. LATITUD: ");
    SerialUSB.print(payload[0], HEX);
    SerialUSB.print(payload[1], HEX);
    SerialUSB.print(payload[2], HEX);
    SerialUSB.println(payload[3], HEX);
    SerialUSB.print(" MIGUEL. LONGITUD: ");
    SerialUSB.print(payload[4], HEX);
    SerialUSB.print(payload[5], HEX);
    SerialUSB.print(payload[6], HEX);
    SerialUSB.println(payload[7], HEX);
    SerialUSB.print(" MIGUEL. Num Sats: ");
    SerialUSB.println(payload[8], HEX);

    return payload[];
}

I want to use 9 bytes of information, first I declare it byte payload[9]; and then I start writing on it. This works well, but now I want to return it for use it in another functions but I can't.


Solution

  • You can't return stack allocated memory from a function. Once the function call ends that data will be reclaimed when the stack pointer is updated. You need to either dynamically allocate the memory on the heap like so ...

    byte* find_fix(){
        byte* payload = new byte[9]; // Allocate memory on the heap
    
        return payload;
    }
    
    void loop() {
        byte* payload = find_fix();
        delete[] payload; // Free memory once it is no longer needed
    }
    

    Or if you know the max size of the array, you can pass in memory to the find_fix function like so ...

    void find_fix(byte* payload) {
        ....
    }
    
    void loop() {
        byte payload[9];
        find_fix(payload);
    }