Static variable (NVS handle) in a file getting overwritten
Posted: Mon Apr 15, 2019 7:13 pm
I am initializing and using a file static nvs handle for getting and setting variables.
I have another file which has a file static char array of 33 bytes. This array is used by another function in this file
Problem: The xNvsHandle handle gets overwritten each time foo is called
Log:
I (28) Init Handle val:: 1
I (118) Get Handle val:: 1
foo() called
I (1148) Set Handle val:: 1177764422
The issue gets solved when I move the cHex array to inside foo() and make it non-static. i.e
Why is this happening?
- static nvs_handle xNvsHandle;
- void vInitNVS()
- {
- esp_err_t err = nvs_flash_init();
- if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
- ESP_ERROR_CHECK(nvs_flash_erase());
- ESP_ERROR_CHECK(nvs_flash_init());
- }
- ESP_ERROR_CHECK(nvs_open(NVS_NAMESPACE_STORAGE, NVS_READWRITE, &xNvsHandle));
- ESP_LOGI("Init Handle val:", "%u", xNvsHandle);
- }
- uint32_t ulGetSeqCounter()
- {
- uint32_t ulSeqCounter;
- ESP_LOGI("Get Handle val:", "%u", xNvsHandle);
- ESP_ERROR_CHECK(nvs_get_u32(xNvsHandle, "seq", &ulSeqCounter));
- return ulSeqCounter;
- }
- void vSetSeqCounter(uint32_t ulSeqCounter)
- {
- ESP_LOGI("Set Handle val:", "%u", xNvsHandle);
- ESP_ERROR_CHECK(nvs_set_u32(xNvsHandle, "seq", ulSeqCounter));
- ESP_ERROR_CHECK(nvs_commit(xNvsHandle));
- }
- static char cHex[33];
- void foo()
- {
- // copy data to cHex ( have ensured that it is null terminated on the 32nd index)
- }
Log:
I (28) Init Handle val:: 1
I (118) Get Handle val:: 1
foo() called
I (1148) Set Handle val:: 1177764422
The issue gets solved when I move the cHex array to inside foo() and make it non-static. i.e
- void foo()
- {
- char cHex[33];
- // copy data to cHex ( have ensured that it is null terminated on the 32nd index)
- }