r/C_Programming • • Sep 12 '26

Question What C function would you delete and rewrite first, and why?

For me it's fnmatch - mostly because it's 40 year's old and smell's funny.

94 Upvotes

238 comments sorted by

View all comments

Show parent comment

1

u/flatfinger Sep 15 '26

My point is that the way clang and gcc process things creates "artificial" side effects whose consequences are totally unpredictable and which directly contradict the behavior of the code as written. Treating a program as a sequence of steps, the above function would never perform any step that would be capable of writing past element 32768 of arr, but the machine code clang and gcc would generate if a function caller ignores the return value could perform an out-of-bounds store.

1

u/Dangerous_Region1682 Sep 16 '26

Oh, I see what you are saying now…

1

u/flatfinger Sep 16 '26

A very important principle in security is "command/data separation". One of the reasons that memory safety is considered fundamental is that out-of-bounds stores that involve "data" can act as arbitrary "commands". IMHO, there should be a dialect of C that respects command/data separation and memory safety invariants. If code does something like:

extern unsigned short ushort1;
int int1 = ushort1*50000/25000;
if (int1 < 50000) actOnLowishNumber(int1);
if (int1 >= 0) actOnNonnegativeNumber(int1);

and ushort1 is 50000, it may be acceptable to either have code call actOnLowishNumber(-71798) or actOnNonnegativeNumber(100000) but the compiler should treat the first line as setting int1 to some particular value, which should then both be both used in the comparisons and passed to the functions.

It's generally not possible for kernel code to guarantee the absence of data races involving storage which is accessible to non-privileged processes. If code does something like:

unsigned test(unsigned short *p)
{
    unsigned short temp = *p;
    temp -= (temp >> 15);
    return temp;
}

it should not be possible for a data race on *p to cause the function to return 65535, but as processed by GCC-ARM when targeting the ARM Cortex-M0, the generated machine code will be equivalent to:

unsigned test(unsigned short *p)
{
    unsigned short temp1 = *p;
    short temp2 = (short)*p;
    temp += (temp2 >> 15);
    return temp;
}

which will yield 65535 if the first read yields 0 and the second yields 65535, or vice versa.