strlen function to empty char* causes reboot

User avatar
gerrikoio
Posts: 8
Joined: Fri Sep 28, 2018 9:41 am

strlen function to empty char* causes reboot

Postby gerrikoio » Wed Aug 07, 2019 3:31 pm

Whether right or wrong, this code is handled by Arduino UNO and Arduino MKR without crashing. It tells me strlen = 1.

With my ESP32 it causes continuous reboot.

Code: Select all

char *thisCharPntr;


void setup() {
  Serial.begin(115200);
  // put your setup code here, to run once:
  Serial.print("Char length: ");
  Serial.println(strlen(thisCharPntr));
}

void loop() {
  // put your main code here, to run repeatedly:

}

ESP_Angus
Posts: 2344
Joined: Sun May 08, 2016 4:11 am

Re: strlen function to empty char* causes reboot

Postby ESP_Angus » Thu Aug 08, 2019 12:00 am

Hi gerrikoio,

This is not a bug in ESP-IDF or Arduino-ESP32.

Because thisCharPntr is a static variable it's initialized to NULL. Evaluating strlen(NULL) involves dereferencing a NULL pointer, and dereferencing a NULL pointer is undefined behaviour in C. (strlen is a C function.)

Undefined behaviour means the implementation is allowed to do whatever it wants. Most computers (including ESP32) will crash. Possibly some implementations don't crash and will instead do something else.

C11 added a new function strlen_s() which has defined behaviour if the pointer is NULL (it returns 0).

Suggesting adding a null-check in your code if you need to verify that thisCharPntr is not-null before calling strlen(NULL)

You can read more about this here: https://stackoverflow.com/a/5796686/1006619

User avatar
gerrikoio
Posts: 8
Joined: Fri Sep 28, 2018 9:41 am

Re: strlen function to empty char* causes reboot

Postby gerrikoio » Thu Aug 08, 2019 10:20 am

Thanks. Your explanation is very clear and most helpful. :D

Who is online

Users browsing this forum: No registered users and 32 guests