werkamsus werkamsus - 3 months ago 13
C++ Question

Memory leak into integer C++

i've added a new function to my code and now an integer i used gets affected by some sort of memory overrun. (Note that this is concerning a .ino Sketch for an Arduino Uno)

Instead of decrementing by 1 with

xPos--;
it decrements by 256
(If i remove the printText function the overrun doesn't happen).

The integer xPos and the char buffer are defined with

int xPos = 0;
char buffer[26];


just under the includes. the u8g.drawStr function draws the string on my display and takes two ints for x and y and a char* as the string as arguments.

void printText(const char* inputText)
{
int y = yPos;
for (int i = strlen(inputText); i > 0; i -= 25)
{
strncpy(buffer, &inputText[strlen(inputText) - i], i >= 25 ? 25 : i);
buffer[26] = '\0';
u8g.drawStr(0, y, buffer);
y += 8;
}
}


Any council would be very appreciated :)

Answer

Your buffer has only 26 slots:

    char buffer[26];

Yet you try to write to its 27th slot:

    buffer[26] = '\0';

That's not going to work. (Zero is the first slot, one is the second slot, and so on. So 26 is the 27th slot.)

Comments