Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Avoid writing in const functions, as it can technically be UB #8462

Closed
6 tasks done
paulocsanz opened this issue Jan 25, 2022 · 0 comments · Fixed by #8463
Closed
6 tasks done

Avoid writing in const functions, as it can technically be UB #8462

paulocsanz opened this issue Jan 25, 2022 · 0 comments · Fixed by #8463

Comments

@paulocsanz
Copy link
Contributor

paulocsanz commented Jan 25, 2022

Basic Infos

  • This issue complies with the issue POLICY doc.
  • I have read the documentation at readthedocs and the issue is not addressed there.
  • I have tested that the issue is present in current master branch (aka latest git).
  • I have searched the issue tracker for a similar issue.
  • If there is a stack dump, I have decoded it.
  • I have filled out all fields below.

Platform

  • Hardware: ESP-12
  • Core Version: current master
  • Development Env: Platformio
  • Operating System: MacOS

Problem Description

This isn't really reproducible, it's more of a theoterical problem. Technically if a variable value is declared as const the compiler can assume it will never change, so changing may trigger UB. Which means doing that in some platforms causes problems, currently to the CPU we target, with the compiler we target, there is no side-effect. And there is no statical analyzer to catch it, it's a silent UB.

Because of SSO the sketch below technically is UB. As described by https://en.cppreference.com/w/cpp/language/const_cast

There also are many real life examples of programs being broken by this, like: https://stackoverflow.com/questions/8954260/const-cast-doesnt-work-c

Of course the circunstances are different, but it's not ideal to live with UB just because it works for now.

String::substring and String::lastIndexOf both do this. Ideally wbuffer() shouldn't be const to avoid this problem happening by accident.

MCVE Sketch

#include <Arduino.h>
void setup() {
  Serial.begin(115200);
  delay(5000);
  const String a(F("Abc"));
  Serial.println(a.substring(2, 3));
  Serial.println(a);
}
void loop() {}
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant