I am learning about pointers and char arrays and was wondering if you could help me find the optimal solution here. I want to avoid using malloc hence I chose to pass a char array to a function by reference where the values are getting filled. In my main.c
char saved_networks[100]; // create an array to save data
readFile123(SPIFFS, "/wifi.txt",saved_networks);
Serial.print("saved networks=");
Serial.println(saved_networks);
And the function:
void readFile123(fs::FS &fs, const char *path, char* return_data)
{
int n=0;
Serial.printf("Reading file: %s\n", path);
File file = fs.open(path);
if (!file || file.isDirectory())
{
Serial.println("Failed to open file for reading");
return;
}
Serial.print("Read from file: ");
while (file.available())
{
char c = file.read();
delayMicroseconds(100);
Serial.print(c);
//strcat(return_data, &c); //returns meditation error
return_data[n]=c;
n=n+1;
}
file.close();
}
In the program above, I create a char array size of 100 and pass it to the function. Inside a function, I read data inside my SPIFFS file system and then assing whatever string I found there to my char array. The code above works however I have 3 questions:
1. Why I cannot use strcat(return_data, &c);
The causes the cpu to crash and return an error:
Stack smashing protect failure!
abort() was called at PC 0x40137793 on core 1
ELF file SHA256: 0000000000000000
2. Why I cannot declare my char array as following : char* saved_networks;
. If I do that, my microcontroller will crash and return an error:
Read from file: TGuru Meditation Error: Core 1 panic'ed (StoreProhibited). Exception was unhandled
3. What is the most optimal way to solve this problem? Since I do not know what will be the maximum size of the data that I read form SPIFFS, simply declaring it size of 100 may not be enough. Is there any way to declare it dynamically ? I assume the only way to do that is by using malloc? Is that true?