iWas-Coder / wge

A multithreaded, high performance, fully functional game engine written in pure C, similar in speed to a Wildebeest™.
https://iwas-coder.github.io/wge
GNU General Public License v3.0
1 stars 1 forks source link

fix: `kstrsub` function array wrong memory access (stack smashing) #30

Closed iWas-Coder closed 10 months ago

iWas-Coder commented 10 months ago

To solve an error in the kstrsub function of the kstring module, this patch is being submitted. The memory access done in dest[start + len] = 0; is not correct, as the wanted substring is len long; thus, it is only needed to terminate the selected substring in dest after the amount of characters specified through the len argument.

Description

Please, include a summary of the changes and which issue(s) is/are fixed. Also include relevant motivation and context. Lastly, list any dependencies that are required for this change.

While predefining unit tests for kstring module (#23), it spit out the error: *** stack smashing detected ***: terminated. This message typically indicates a buffer overflow. This happens when you write more data to a block of memory (like an array) than it can hold; basically, when a program uses more stack memory than it's allowed to.

The issue is in the line containing: dest[start + len] = 0;. Here, it's trying to set the character at the index start + len to null, i.e. mark the string as terminated at that specific point. However, the specific substring wanted to obtain is exactly len chars long, so there is no point in terminating the dest array start more chars than it needs: appart from being innecessary, if the dest array is less than start + len long (perfectly feasible as the wanted substring to hold there is only len chars long), it will try to write past the end of dest, causing a buffer overflow.

Issues:

Development and testing equipment

Development PC specs:

Type of change

Checklist:

iWas-Coder commented 10 months ago

Let's merge it now as #23 depends on this bugfix to work properly.