c++ - 从函数返回 char 数组时崩溃
问题描述
我和一个朋友正在一个 ESP32 网络服务器上工作,我们碰壁了。我的哥们几乎已经放弃了,我的技术不如他。
我们有以下函数,它们编译得很好,但会导致 ESP32 崩溃。经过大量调试后,我很确定尝试返回时会发生崩溃c
void handle_logs_view(String path){
char** list = sdcard_list_files(path);
for (int i=0;list[i]!=NULL;i++){
Serial.println(list[i]);
}
}
char** sdcard_list_files(String path){
Serial.println("Listing files for "+path);
if (path.compareTo("/")){
char* c[]={"dir1","file1.log","file2.log","file3.log","file4.log","file5.log",NULL};
return c;
}
return NULL;
}
#endif
异常解码器的结果如下:
PC: 0x400d1d1b: handle_logs_view(String) at C:\Users\MickW\Downloads\Front_End-11_create_file_explorer\Front_End-11_create_file_explorer\sample_code\WIFITest/WIFITest.ino line 45
EXCVADDR: 0x00000000
Decoding stack results
0x400d1d1b: handle_logs_view(String) at C:\Users\MickW\Downloads\Front_End-11_create_file_explorer\Front_End-11_create_file_explorer\sample_code\WIFITest/WIFITest.ino line 45
0x400d1e7e: std::_Function_handler >::_M_invoke(const std::_Any_data &) at C:\Users\MickW\AppData\Local\Temp\arduino_build_351256\sketch\WebServer.cpp line 32
0x400d68ff: std::function ::operator()() const at c:\users\mickw\appdata\local\arduino15\packages\esp32\tools\xtensa-esp32-elf-gcc\1.22.0-97-gc752ad5-5.2.0\xtensa-esp32-elf\include\c++\5.2.0/functional line 2271
0x400d69a5: FunctionRequestHandler::handle(WebServer&, HTTPMethod, String) at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\libraries\WebServer\src\detail/RequestHandlersImpl.h line 45
0x400d6a12: WebServer::_handleRequest() at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\libraries\WebServer\src\WebServer.cpp line 633
0x400d6b8d: WebServer::handleClient() at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\libraries\WebServer\src\WebServer.cpp line 314
0x400d1d6e: loop() at C:\Users\MickW\Downloads\Front_End-11_create_file_explorer\Front_End-11_create_file_explorer\sample_code\WIFITest/WIFITest.ino line 22
0x400d8ad5: loopTask(void*) at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\cores\esp32\main.cpp line 23
0x40089552: vPortTaskWrapper at /Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/freertos/port.c line 143
这是来自 espressif 网站:
LoadProhibited, StoreProhibited
当应用程序尝试读取或写入无效内存位置时,会发生此 CPU 异常。写入/读取的地址在寄存器转储的 EXCVADDR 寄存器中找到。如果此地址为零,则通常意味着应用程序试图取消引用 NULL 指针。
我会很感激任何帮助或建议
解决方案
您正在返回一个指向自动(即基于堆栈)变量的指针。该变量在返回时消失sdcard_list_files
,使指针“悬空”。
一种解决方案是声明c
为static
. 另一个(在 C++ 中)将返回一个std::optional <std::array<std::string>, 6>>
.
推荐阅读
- tensorflow - 你能从 tf.keras.Adam 中提取当前的学习率吗?
- linkedin - 哪个合作伙伴计划适合使用 v2 API 简单地访问 r_basicprofile?
- struct - 使用包含参数的 SystemVerilog 结构作为模块的输入/输出端口
- sql - 为什么 -10 / 500 = 0 在 SQL 中?
- ios - 将#selector 存储在变量中
- django - 为房地产设计 django 模型
- javascript - 尝试将等待函数的返回值设置为常量时接收未定义
- java - 如何在Java中通过void equals找到String中的特殊符号
- google-bigquery - 尝试在 BigQuery 中查询多个表时列名不明确
- reactjs - 如何在 React 中使用数组更新嵌套状态?