Static variable (NVS handle) in a file getting overwritten

taruroy
Posts: 3
Joined: Thu Feb 07, 2019 1:14 am

Static variable (NVS handle) in a file getting overwritten

Postby taruroy » Mon Apr 15, 2019 7:13 pm

I am initializing and using a file static nvs handle for getting and setting variables.
  1. static nvs_handle xNvsHandle;
  2.  
  3. void vInitNVS()
  4. {
  5.     esp_err_t err = nvs_flash_init();
  6.     if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  7.         ESP_ERROR_CHECK(nvs_flash_erase());
  8.         ESP_ERROR_CHECK(nvs_flash_init());
  9.     }
  10.     ESP_ERROR_CHECK(nvs_open(NVS_NAMESPACE_STORAGE, NVS_READWRITE, &xNvsHandle));
  11.     ESP_LOGI("Init Handle val:", "%u", xNvsHandle);
  12. }
  13.  
  14. uint32_t ulGetSeqCounter()
  15. {
  16.     uint32_t ulSeqCounter;
  17.     ESP_LOGI("Get Handle val:", "%u", xNvsHandle);
  18.     ESP_ERROR_CHECK(nvs_get_u32(xNvsHandle, "seq", &ulSeqCounter));
  19.     return ulSeqCounter;
  20. }
  21.  
  22. void vSetSeqCounter(uint32_t ulSeqCounter)
  23. {
  24.     ESP_LOGI("Set Handle val:", "%u", xNvsHandle);
  25.     ESP_ERROR_CHECK(nvs_set_u32(xNvsHandle, "seq", ulSeqCounter));
  26.     ESP_ERROR_CHECK(nvs_commit(xNvsHandle));
  27. }
I have another file which has a file static char array of 33 bytes. This array is used by another function in this file
  1. static char cHex[33];
  2.  
  3. void foo()
  4. {
  5.       // copy data to cHex ( have ensured that it is null terminated on the 32nd index)
  6. }
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
  1. void foo()
  2. {
  3.        char cHex[33];
  4.       // copy data to cHex ( have ensured that it is null terminated on the 32nd index)
  5. }
Why is this happening?

User avatar
fly135
Posts: 606
Joined: Wed Jan 03, 2018 8:33 pm
Location: Orlando, FL

Re: Static variable (NVS handle) in a file getting overwritten

Postby fly135 » Tue Apr 16, 2019 3:36 pm

The most obvious answer is that you are writing past the end of cHex.

Who is online

Users browsing this forum: Baidu [Spider] and 133 guests