【发布时间】:2021-09-20 09:26:31
【问题描述】:
我正在为 Arduino (ESP8266) 编写代码,并且必须从文件中读取一个字符串才能使用它。我不知道那个文件有多长,所以我必须创建一个char* 并将其传递给readConf 函数,以便malloc 决定内存大小。
void readConf(char path[], char **buff){
SPIFFS.begin();
if (SPIFFS.exists(path))
{
File file = SPIFFS.open(path, "r");
int size = file.size();
Serial.print("File size: ");
Serial.println(size);
char *bu;
bu = (char*) malloc((size+1) * sizeof(char));
file.read((uint8_t*) bu, size);
bu[size] = '\0';
Serial.print("Data: ");
for (int i = 0; i < size; i++)
Serial.print(bu[i]);
Serial.println("");
//Everything is OK. It is printed correctly.
buff = &bu; //!This is the problem!
file.close();
}
SPIFFS.end();
}
#define file_path "/file"
void setup(){
if(WiFi.getMode() != WIFI_STA)
WiFi.mode(WIFI_STA);
char* username;
readConf(file_path, &username);
char* password;
readConf(file_path, &password);
/*The same with password. */
WiFi.begin(username, password);
Serial.print("username: ");
Serial.println(username); //Here I sometimes get Exception, and sometimes prints non-sense characters
free(username); //My memory is limited. I'm doing all this stuff for this line!
//...
}
我也在StackOverflow和其他网站上搜索了很多,也使用了char *,char **,直接在readConf函数中填充指针,还有很多但没有一个起作用。我应该如何处理?我能做到吗?
注意:我不应该使用 String 类。
【问题讨论】:
-
改用
*buff = bu。或者,如果您真的在使用 C++ 编程,请使用 实际 引用而不是指针来模拟引用。 -
@Someprogrammerdude 我以前遇到很多硬件异常,结果Arduino会一次又一次地重启。我必须这样使用它。
-
顺便问一下,为什么你现在使用 Arduino 标准
String类作为你的字符串? -
@Someprogrammerdude 硬件异常:)) 我有同样的错误:stackoverflow.com/questions/60966280/…,所以stackoverflow.com/a/60969009/9691976 说:
This error pattern is typical for the String class.