Skip to content

Commit 6ea02ec

Browse files
committed
Fix: correct return type and PSRAM handling in nvs_config_get_string()
1 parent b262683 commit 6ea02ec

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

main/nvs_config.cpp

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ typedef struct {
3838
static ConfigCacheEntry* config_cache = nullptr;
3939
static SemaphoreHandle_t config_mutex = nullptr;
4040

41+
// Duplicates a string into specified memory (PSRAM) using heap_caps_malloc().
42+
static char* heap_caps_strdup(const char* src, uint32_t caps) {
43+
if (!src) return nullptr;
44+
size_t len = strlen(src) + 1;
45+
char* dst = (char*) heap_caps_malloc(len, caps);
46+
if (dst) memcpy(dst, src, len);
47+
return dst;
48+
}
49+
4150
// --- Initialize cache and mutex ---
4251
void init_cache() {
4352
if (!config_mutex) {
@@ -76,17 +85,18 @@ static ConfigCacheEntry* get_cache_entry(const char* key, config_type_t type) {
7685
}
7786

7887
// --- API Functions ---
79-
const char *nvs_config_get_string(const char *key, const char *default_value) {
88+
char *nvs_config_get_string(const char *key, const char *default_value) {
8089
CONFIG_LOCK();
8190
ConfigCacheEntry* entry = get_cache_entry(key, CONFIG_TYPE_STRING);
8291
if (!entry) {
8392
CONFIG_UNLOCK();
84-
return default_value ? default_value : ""; // Return default or empty string, but never NULL
93+
const char* fallback = default_value ? default_value : ""; // Return default or empty string, but never NULL
94+
return heap_caps_strdup(fallback, MALLOC_CAP_SPIRAM);
8595
}
8696

8797
if (entry->valid) {
8898
ESP_LOGD(TAG, "Cache hit for string key: %s", key);
89-
const char* result = entry->data.str_value;
99+
char* result = heap_caps_strdup(entry->data.str_value, MALLOC_CAP_SPIRAM);
90100
CONFIG_UNLOCK();
91101
return result;
92102
}
@@ -123,7 +133,7 @@ const char *nvs_config_get_string(const char *key, const char *default_value) {
123133
entry->data.str_value = loaded_value;
124134
entry->valid = true;
125135

126-
const char* result = entry->data.str_value;
136+
char* result = heap_caps_strdup(loaded_value, MALLOC_CAP_SPIRAM);
127137
CONFIG_UNLOCK();
128138
return result;
129139
}

main/nvs_config.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,5 +172,5 @@ namespace Config {
172172
void init_cache(); // Allocate PSRAM-backed cache and mutex
173173
void flush_nvs_changes(); // Flush cached config values to NVS
174174
bool has_dirty(); // Check if any cached values are dirty
175-
void dump_cache_status() // in case we want to monitor the nvs-cache - not used currently
175+
void dump_cache_status(); // in case we want to monitor the nvs-cache - not used currently
176176
}

0 commit comments

Comments
 (0)