警告:返回局部变量地址 'buffer'

warning: address of local variable 'buffer' returned

我正在做一个 Arduino 项目,我需要使用 HMC5883L 传感器的库。问题是这些库有点旧,我的编译器抱怨函数中的 'return':

/home/leandro/arduino-1.6.1/libraries/HMC5883L/HMC5883L.cpp: In member function 'uint8_t* HMC5883L::Read(int, int)':
/home/leandro/arduino-1.6.1/libraries/HMC5883L/HMC5883L.cpp:124:11: warning: address of local variable 'buffer' returned [-Wreturn-local-addr]
uint8_t buffer[length];

部分代码为:

HMC5883L.cpp

uint8_t* HMC5883L::Read(int address, int length)
{
  Wire.beginTransmission(HMC5883L_Address);
  Wire.write(address);
  Wire.endTransmission();

  Wire.beginTransmission(HMC5883L_Address);
  Wire.requestFrom(HMC5883L_Address, length);

  uint8_t buffer[length]; // Here is line 124
  if(Wire.available() == length)
  {
      for(uint8_t i = 0; i < length; i++)
      {
          buffer[i] = Wire.read();
      }
  }
  Wire.endTransmission();

  return buffer;
}

HMC5883L.h:

#ifndef HMC5883L_h
#define HMC5883L_h

#include <Arduino.h>
#include <Wire.h>

#define HMC5883L_Address 0x1E
#define ConfigurationRegisterA 0x00
#define ConfigurationRegisterB 0x01
#define ModeRegister 0x02
#define DataRegisterBegin 0x03

#define Measurement_Continuous 0x00
#define Measurement_SingleShot 0x01
#define Measurement_Idle 0x03

#define ErrorCode_1 "Entered scale was not valid, valid gauss values are: 0.88, 1.3, 1.9, 2.5, 4.0, 4.7, 5.6, 8.1"
#define ErrorCode_1_Num 1

struct MagnetometerScaled
{
    float XAxis;
    float YAxis;
    float ZAxis;
};

struct MagnetometerRaw
{
    int XAxis;
    int YAxis;
    int ZAxis;
};

class HMC5883L
{
    public:
      HMC5883L();

      MagnetometerRaw ReadRawAxis();
      MagnetometerScaled ReadScaledAxis();

      int SetMeasurementMode(uint8_t mode);
      int SetScale(float gauss);

      const char* GetErrorText(int errorCode);

    protected:
      void Write(int address, int byte);
      uint8_t* Read(int address, int length);

    private:
      float m_Scale;
};
#endif

我尝试了 here, here and here 的一些建议但没有成功。也许我只是想不出如何使用这些建议来解决这个问题。

编辑:我的代码有错别字,刚刚改了。

一个简单的解决方案是修改库文件并将缓冲区声明为staticstatic 关键字告诉编译器该变量将在执行离开函数后继续存在。因为它在退出函数后仍然存在,所以地址仍然有效。

解决方案 1

而不是

uint8_t buffer[length]; // Here is line 124

使用:

// Allocate memory from the heap.
uint8_t* buffer = new unit8_t[length];

确保在调用函数中释放内存。

解决方案 2

期望输入来自调用函数。

uint8_t* HMC5883L::Read(int address, int length, uint8_t buffer[])

这是因为你在堆栈上声明了缓冲区。如果你想 return 一个动态分配的缓冲区,使用 malloc:

uint8_t *buffer = new uint8_t[length];
if (buffer == NULL) error_allocation;

// Make sure to de-allocate after you finish to use it
delete [] buffer;