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

Memory safety (use after free) issue in nk_buffer_realloc #768

Open
linkdd opened this issue Feb 2, 2025 · 0 comments
Open

Memory safety (use after free) issue in nk_buffer_realloc #768

linkdd opened this issue Feb 2, 2025 · 0 comments

Comments

@linkdd
Copy link

linkdd commented Feb 2, 2025

Actual Behavior

The nk_allocator interface requires an allocation function which takes a pointer as argument. This suggests that we should use realloc() if said pointer is not NULL (but the default implementation actually ignores this argument, and simply use malloc()).

In the function nk_buffer_realloc(), there is a call to the allocation function which passes the buffer memory as argument. But then, if the result of this function is different from the old buffer memory pointer, the old pointer is freed:

https://github.com/Immediate-Mode-UI/Nuklear/blob/master/nuklear.h#L8592-L8595

This is introduce a memory safety issue (use after free). The realloc() function might return the same memory block at a different address:

https://manpages.org/realloc/3

The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any built-in type and may be different from ptr, or NULL if the request fails.

This means that if realloc() moves the pointer (and it often does), the nk_buffer_realloc() will free what it expects to be another allocation, and then the rest of the lib will try to use an allocation that was actually freed.

Desired Behavior

Option 1: You should only check for NULL and trust the behavior of nk_buffer_realloc() (which would rely on realloc() instead of malloc(), no more free+memcpy.

Option 2: Remove the ptr argument of the nk_plugin_alloc callback, so that it is 100% clear that realloc() is not expected here.

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