In the following code, display_buffer and splash are each declared to be 20 characters in length. dsplash is 21 characters. The result is two lines of output:
Hello There World!
Oh Hello There World!
I was expecting an error, given that the size of dsplash exceeds the size initially declared for display_buffer. It seems that the size of display_buffer was dynamically increased. Am I failing to understand what is really happening here? Perhaps the compiler sees that I am putting 21 characters into an array that I declared as 20 characters, and therefore re-sizes the array, at compile time, to accommodate.
My question is whether this presents any danger, as far as memory management is concerned? Is there a way to specify the size of a char array such that it will not be resized dynamically? (And, therefore, would throw an error at compile time.)
The ultimate goal is to send an array of char array to an oled display that has a limit (given how I am configuring it) of 20 characters/line, and I want to be sure that I am not overloading any of the lines.
char display_buffer[] = " ";
char splash[] = "Hello There World! ";
char dsplash[] = "Oh Hello There World!";
void setup() {
Serial.begin(9600);
sprintf(display_buffer, "%s", splash);
Serial.println(display_buffer);
sprintf(display_buffer, "%s", dsplash);
Serial.println(display_buffer);
}
void loop() {
// put your main code here, to run repeatedly:
}
/var/folders/4z/3g9th3gs4cng3b803dg5bhw40000gn/T/arduino_modified_sketch_218003/Blink.ino: In function 'void setup()':
Blink:7:27: error: 'sprintf' may write a terminating nul past the end of the destination [-Werror=format-overflow=]
sprintf(display_buffer, "%s", dsplash);
^~~~
/var/folders/4z/3g9th3gs4cng3b803dg5bhw40000gn/T/arduino_modified_sketch_218003/Blink.ino:7:10: note: 'sprintf' output between 1 and 22 bytes into a destination of size 21
sprintf(display_buffer, "%s", dsplash);
~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1plus: some warnings being treated as errors
exit status 1
'sprintf' may write a terminating nul past the end of the destination [-Werror=format-overflow=]