Skip to content

Bugfix communication.cpp : guard against buffer[-1] when newline is first byte#6

Open
hubertciebiada wants to merge 1 commit intoSurfGargano:masterfrom
hubertciebiada:fix/communication-buffer-underread
Open

Bugfix communication.cpp : guard against buffer[-1] when newline is first byte#6
hubertciebiada wants to merge 1 commit intoSurfGargano:masterfrom
hubertciebiada:fix/communication-buffer-underread

Conversation

@hubertciebiada
Copy link
Copy Markdown

Problem

software_stm32/src/communication.cpp:207 accesses buffer[c-1] without checking that c > 0:

for (unsigned int c = 0; c < buflen; c++) {
    if (buffer[c] == '\n') {
        if (buffer[c-1] == '\r') buffer[c-1] = '\0';
        ...
    }
}

When c == 0 and the first byte happens to be \n, buffer[c-1] reads buffer[-1] — out of bounds. This is undefined behaviour per the C/C++ standard.

In practice it is unlikely (the outer guard if (buflen >= 5) and the convention that ESP32 sends \r\n make a leading \n rare), but it can happen on UART glitches, partial frames, or right after reset. On STM32 this typically reads stack/heap memory that happens to sit just before buffer, so the comparison may spuriously succeed and the code then writes '\0' to that out-of-bounds location too — silent memory corruption.

Fix

Add c > 0 && to the condition. One-line defensive guard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant