简体   繁体   中英

Passing const char* variables to a function

I'm having a weird and unexpected result in my code and I'd like your support to explain me what happens here.

I have a structure of a confiration:

struct sConfig {
  const char* ssid;
  const char* password;
}

I'm loading this configuration using LittleFS from a deserialized json: config.ssid = json["ssid"]; // so this is coming from the FS in a json file config.password = json["password"]; // so this is coming from the FS in a json file

So far, all is fine, I can print out the value using Serial.println(config.ssid);

I'm then calling an internal void function

startWiFi(config.ssid, config.password);
void startWiFi(const char* ssid, const char* psswd) {
  Serial.println(ssid);
  Serial.println(psswd);
}

As a result, the console returns: and ?:⸮?@⸮8⸮?<9⸮?⸮8⸮?:⸮?@⸮8⸮?<9⸮?⸮8⸮?:⸮?@⸮8⸮?<9⸮?⸮8⸮?.:⸮?@⸮

What can be wrong in my variables? Please help me as I'm stuck.

Thanks a lot.

To fix the issue I'd avoid copying a pointer and copy the actual data.
So, instead of config.password = json["password"]; I'd declare ssid and password as char arrays and copy the values from the json with strncpy()

struct sConfig {
    char ssid[32];
    char password[64];
}

or I'd allocate them on the spot with a custom copy function

char * myCopy (char *destination, const char *source)
{
    // I'm using 64 because is the max length of WPA2-PSK passwords
    size_t len = strnlen(destination, 64);
    destination = malloc((num + 1) * sizeof(char));
    strncpy(destination, source, num);

    return destination;
}
....
myCopy(config.ssid,     json["ssid"]);
myCopy(config.password, json["password"]);

What's probably happening here is a use-after-free bug.

At config.ssid = json["ssid"] you copy a pointer to the internal memory of the json object. It's probably valid at the time of that copy (so the print succeeds), but when the json changes its state or gets deallocated, you get garbage at that memory address.

The solution is - as suggested in the other answer - copy the whole string and not just its address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM