Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Potential Memory Issue: Returning Pointer to Stack Data in readAndReturn() #9

Open
edwin-oetelaar opened this issue Feb 1, 2025 · 0 comments

Comments

@edwin-oetelaar
Copy link

I have noticed a potential issue in the driver code for the AD7606. In the readAndReturn() method (for example, in the AD7606_8080 class), a pointer is returned to a locally declared array which resides on the stack. Here is an excerpt from the code:

int16_t * AD7606_8080::readAndReturn()
{
    int16_t rawDataBuffer[8]; // This data is only valid inside the function, it is on the STACK
    // ... code to populate rawDataBuffer ...
    return rawDataBuffer;
}

Because rawDataBuffer is allocated on the stack, its lifetime is limited to the duration of the function call. Returning a pointer to this buffer leads to undefined behavior since the data becomes invalid once the function returns.

One workaround could be to declare rawDataBuffer as static, which would extend its lifetime beyond the function scope. However, please note that while this might work in a single-threaded context, it can introduce issues with reentrancy and thread safety.

I have noticed this pattern repeated in other parts of the codebase as well. It might be worthwhile to review these instances to ensure that all returned pointers reference valid memory. A more robust solution might be to have the caller supply a buffer or to use dynamic memory allocation (with proper memory management).

Thank you for your attention to this matter.

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

No branches or pull requests

1 participant