Immediate-Mode-UI / Immediate-Mode-UI/Nuklear

Undefined behavior in the implementation of `nk_ptr_add`

Open
#763 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C
Stars
11.4k
Forks
686
Avg merge
4d 1h
Merged PRs (30d)
3

Description

On adding an integer to a pointer, the C standard says

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

This means this usage of nk_ptr_add triggers undefined behavior when b->size < size because it causes an overflow, and this can happen when the buffer needs to grow. In fact, I caught this error when trying to compile and run Nuklear for a Zig project, since Zig catches various kinds of undefined behavior in debug mode.

I think the solution is to cast the i parameter of nk_ptr_add to a signed type like ptrdiff_t to avoid the overflow. This requires adding a new type to the list of integer types here.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in nuklear.h at nk_ptr_add and inspect the integer type definitions around lines 418-427, then follow its use near line 8630. Verify the pointer arithmetic when the buffer grows and b-size is less than size; done means the operation no longer invokes signed or unsigned overflow under the stated case.

Written by the indexing model from the issue text.

Assessment

Tech stack
c
Domain
frontend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.