r/ProgrammingLanguages • C3 - http://c3-lang.org • May 03 '26

Blog post Unsigned Sizes: A Five Year Mistake

https://c3-lang.org/blog/unsigned-sizes-a-five-year-mistake/
91 Upvotes

115 comments sorted by

View all comments

Show parent comment

2

u/EggplantExtra4946 May 05 '26

just too many edge cases

Like what?

and security issues

Unsigned integers are easier to reason with. It's easy to verify that underflow do not occur.

Unsigned types sound simple, but they are not.

This is complete non sense.

1

u/Tasty_Replacement_29 Bau May 05 '26 edited May 05 '26

OK, here are few edge cases and security issues:

  • The following loop will never terminate: int n = 100; for (unsigned i = n - 1; i >= 0; i--) { printf("%d\n", i); }. It is quite tricky to implement this type of loop correctly.
  • Consider the following. What does it print? int a = -1; unsigned int b = 1; if (a < b) printf("a is less than b\n"); else printf("b is less than a\n"); If you need to think about it, then you have already an issue: It should be obvious without thinking.
  • This is dangerous: int *ptr = malloc(count * sizeof(int)); because the allocated size might be too small, without error. With signed, it would be easy to catch the problem.
  • All the comparisons of unsigned values are edge cases. Each time you write x > a or x >= a or x < b you have an edge case of underflow / wraparound, which you don't have if you use signed.

It's easy to verify that underflow do not occur.

How do you do that? You can not use >= 0.

Unsigned types sound simple, but they are not.

For example, operations where you have both signed and unsigned. Do you disallow it, or do you log a warning, or what do you do? This is specially tricky if you use type inference: i := 1 is this signed or unsigned? Whatever you pick, you can then have a challenge if you mix unsigned with signed values.

Signed integer also have overflow and underflow, but the edge cases are much, much farther away than for unsigned integers, where they are very close to a value that is used very often: just next to 0. Unsigned underflow is near everyday values, and signed overflow is near extreme values.

BTW thanks for writing; I think I know understand why my comment was downvoted: I didn't write it clear enough. I hope the above is more clear, if not, please let me know!

1

u/EggplantExtra4946 May 05 '26 edited May 05 '26

The following loop will never terminate It is quite tricky to implement this type of loop correctly.

You can iterate backwards like this:

for (size_t i = length; i > 0; i--) {
    array[i-1]
}

or eventually like this:

for (size_t i = length-1; i > 0; i--) { array[i] } array[0]

Consider the following. What does it print?

Mixing signed and unsigned integers like that is a receipe for failure. C allows that but a decent type system shouldn't. The real issue is C's type system poor handling of integers, it's not the fault of unsigned integers.

This is dangerous: int *ptr = malloc(count * sizeof(int)); because the allocated size might be too small, without error.

Again, type system issue and count (and sizes) should be unsigned in the first place. (Also any interger literal imo, unless the interal is negated in which case it should be a signed.)

How do you do that? You can not use >= 0.

If you're doing a substraction you can compare the operands before doing the substraction. But frankly I used unsigned integers everywhere, always have overflow/underflow in the back my mind and "checking for underflow" is just something that doesn't come up. If anything, when it does come up, when a substraction can result in a negative number I'll let it wrap around, knowing that if I need to add that substraction result to an unsigned integer, the addition will overflow and effectively perform a substraction and give the correct result, thanks to the arithmetic properties of unsigned integer wrapping. That's precisely what makes unsigned integers easy to work with, even in the eventual case of an underflow. Effectively underflows just doesn't really matter in result of temporary expressions, concerning the correctness of the overall expression. Overflows are the real issues but if you pick width large enough it shouldn't happen. For completeness, a double underflow would be another issue but if you're using unsigned integers because the quantity (such as memory length/size) can't be negative, you're going to only have the one subtraction, no 5 in a row. Or if you do you can refactor a - b - c - d - e into a - (b + c + d + e).

For example, operations where you have both signed and unsigned. Do you disallow it, or do you log a warning, or what do you do?

The type system should disallow it, unless unsigned numbers is narrower than the signed integer, or if you know that the signed integer is positive, etc.. Like others have said ITT.

This is specially tricky if you use type inference: i := 1 is this signed or unsigned?

What I do in my language is make all integer literals unsigned with the narrower width that can contain them, but if the integer literal is negated, I constant fold it and set the type of the resulting number to signed, with the same width.

I think I know understand why my comment was downvoted: I didn't write it clear enough.

Nah it's clear enough, you're downvoted because of the meaning of your arguments, not because of your form.

Another reason for unsigned is that optimizing compilers of C/C++ won't break your code beacuse they feel they can do whatever they want in the case of undefined behavior and basically all signed arithmetic operations are (or were, maybe not true in new standards) UB upon overflow/underflow.

1

u/Tasty_Replacement_29 Bau May 06 '26

> You can iterate backwards like this

Yes, you can. You can. But can all the others? With signed integers, things like that are much less of an issue. James Gosling (designer of Java): "[...] For me as a language designer, [...], what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. [...] Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex."

> Again, type system issue and count (and sizes) should be unsigned in the first place.

Maybe you are not aware of this issue then. So you have code like this (printf for illustration):

size_t count = 1000000000;
size_t size = sizeof(int);
printf("array size: %u\n", count * sizeof(int));
int *ptr = malloc(count * sizeof(int));
printf("pointer: %p\n", ptr);

That works, any maybe you get:

array size: 4000000000
pointer: 0x715f4fd68010

But now if you try this:

size_t count = 1073741824;
size_t size = sizeof(int);
printf("array size: %u\n", count * sizeof(int));
int *ptr = malloc(count * sizeof(int));
printf("pointer: %p\n", ptr);

You get something like this:

array size: 0
pointer: 0x7ceab467a010

So the pointer is still valid, it just happens to allocate zero bytes. So you can't use the return value to check whether it worked.

operations where you have both signed and unsigned The type system should disallow it

Right. The problem now is: unsigned is supported, and so now many developers use unsigned, return unsigned in their library etc. And then you have to do operations on them (add, multiply etc.). If the default type is signed (via type inference), how do you do that? Do you cast the signed to unsigned, or the unsigned to signed? It's more work, you have to think about it, and you have two choices. If you don't have unsigned, then the problem goes away.

Nah it's clear enough, you're downvoted because of the meaning of your arguments, not because of your form.

I see that now, but no it was not clear to me... I thought more people know about the problems of unsigned...

Another reason for unsigned is that optimizing compilers of C/C++ won't break your code beacuse they feel they can do whatever they want in the case of undefined behavior and basically all signed arithmetic operations are (or were, maybe not true in new standards) UB upon overflow/underflow.

In theory you are right. In practice, C/C++ compilers did the obvious thing, because it's the easiest and fastest. As for the standard, with C++11 this is mostly fixed ("signed integer type with width of exactly 8, 16, 32 and 64 bits respectively with no padding bits and using 2's complement for negative values (provided only if the implementation directly supports the type").

But we don't need to argue about the mistakes of other languages :-)

I do think that maybe "byte" in my language should be unsigned, to avoid having to type "& 0xff" each time. I don't think this should be a problem.

2

u/flatfinger May 06 '26

Ask any Pascal developer how Byte works, and compare the task of e.g. trying to assemble two octets when into a 16-bit value when using Pascal's Byte type versus Java's. Nearly all of the problems with unsigned types in C involve either types that are not smaller than int, or the failure of the Standard to specify that on quiet wraparound two's-complement systems the results of a signed integer addition, subtraction, or multiplication will behave as a numbers congruent to the mathematically correct value, mod the number of distinct values.

1

u/EggplantExtra4946 May 07 '26

Yes, you can. You can. But can all the others?

You are being ridiculous. And also there is a simpler way: for (size_t i = length-1; i < length; i--) { array[i] }

Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex

James Gosling or not I doubt that this is true.

Maybe you are not aware of this issue then. So you have code like this (printf for illustration):

How are integer overflows in multiplications a problem about unsigned integers exactly and how come signed integers wouldn't have the exact same problem?

So you can't use the return value to check whether it worked.

Except that malloc malloc worked as expected. Again this has absolutely nothing to do with unsigned integers.

unsigned is supported

The idea that it wouldn't be supported is ridiculous.

The problem now is: unsigned is supported, and so now many developers use unsigned, return unsigned in their library etc

Stop it with your hysteria. Unsigned integers are used, so what?

If the default type is signed (via type inference),

If your type system/type infererence system is too rigid it's your fault. There is no reason why 0, 1, 2, 3, 4, 0x100, 0x1000 should necessarily be signed and why those literals couldn't be safely implicitly casted to unsigned or vice versa.

Do you cast the signed to unsigned, or the unsigned to signed?

Yes but if you want to mix signed and unsigned there is a problem with the coherency of your program. Almost everytime this situations like these will arise is if you insist on using signed in the first place which you don't need at all for general purpose programming, aka strings, buffers, arrays, data structures, etc..

If you don't have unsigned, then the problem goes away.

This so fucking stupid how is it even an solution? For one thing you're not removing jack shit because signed and unsigned cpu instruction (and therefore the bit pattern semantics of the corresponding language operators) are the exact same, except for comparisons and right shift. Also things like multiplcations where the result has twice the width of the operands but languages don't support that.

You need unsigned comparisons, you need logical right shift, you need zero extensions.

When you read a byte from a string, you want to do if (byte < 0x80), you can't do that with int8_t.

You are being dishonnest about the problem of mixing signed and unsigned. Clearly you think this is unsigned's fault, you never consider that signed integers are equally at fault. Maybe the issue is that you use signed everywhere.

I can't even see why you would use signed integers anyway. For the arithmetic you need to do for usual memory and data structure operations, signed integers have no use. In a program for converting fahrenheit to celsius degree I would use signed integers, but for writing an interpreter or compiler? Nope.

2

u/Tasty_Replacement_29 Bau May 07 '26

Ah I missed this message sorry.

> You are being ridiculous.

No, I'm serious.

> And also there is a simpler way

Both options are not simple. The simple and obvious way is not working because of unsigned.

> James Gosling or not I doubt that this is true.

I do not doubt that this is true. I agree with James Gosling. It doesn't mean you have to agree, right. But you should not call me or James Gosling ridiculous if we don't agree. I don't call you ridiculous either.

> How are integer overflows in multiplications a problem about unsigned integers exactly

They are a problem because there is no way to detect them with unsigned: the result of the multiplication is still positive. With signed, if there is an overflow, then the result of the multiplication is negative, and you can detect that easily.

> Except that malloc malloc worked as expected. Again this has absolutely nothing to do with unsigned integers.

Sure, the problem was the usage of unsigned multiplication. That's my point: the problem wouldn't be there if size_t is signed. See also https://vorpus.org/blog/why-does-calloc-exist/

> Stop it with your hysteria. Unsigned integers are used, so what?

I'm not hysteric. The problem is that unsigned integers are used, yes.

> This so fucking stupid how is it even an solution?

This is not fucking stupid, it is a solution.

> You are being dishonnest about the problem of mixing signed and unsigned.

No, I am not.

> Clearly you think this is unsigned's fault, you never consider that signed integers are equally at fault.

Yes, the problem is unsigned integers in this case.

> I can't even see why you would use signed integers anyway.

Well, with signed integers you would be able to:

  • Do the obvious loop for (size_t i = length-1; i < length; i--) { array[i] }
  • malloc would be able to detect the overflow at malloc(count * sizeof(int));

2

u/flatfinger May 07 '26

With signed, if there is an overflow, then the result of the multiplication is negative, and you can detect that easily.

A multiplication of positive numbers that overflows may yield a negative result, but it need not do so. When using 32-bit math, multiplying 65537 by 65537 will yield 131073.

When performing addition of unsigned numbers, wraparound may be detected by comparing the result with either source operand (in case of wraparound it will be less than both). When subtracting unsigned numbers, wraparound may be detected by comparing the result with the left operand (in case of wraparound it will be greater).

1

u/EggplantExtra4946 May 07 '26 edited May 07 '26

you should not call me or James Gosling ridiculous if we don't agree. I don't call you ridiculous either.

It's true that it is techically an edge case but unsigned underflow is much less hard to understand and to deal with than sign underflow/overflow. With signed, you need to conside wheter the 2 numbers were positive, negative, one one positive and one negative. If some programmers can't grasp what unsigned underflow/overflow there is no way in hell than they should fully understand all the signed overflow/underflow edge cases and how to deal with them. I for one, can't really claim to understand the signed integer edge cases, but I do understand unsigned integers edge cases, because it is simpler.

I don't think it's fair to call the loop example a deal breaker, iterating in reverse is not that common, it's not hard to solve, it's simpler to solve that signed integer edge cases.

The larger point is that bounds checking is simpler with unsigned integers and god knows how much important this is. With unsigned integers you only need one simple bound check: if (index < length) or if (index + elem_length <= length), but with signed intgers there is always the additional possibility that the input was a negative numbers, always the possibility of a sign overflow. With unsigned, even you have an overflow, you're going to have a bug but at least you will still not have an out-of-bounds memory access, but with signed integers you're allowing possible out-of-bounds access. Integer overflows are a whole class of vulnerabilities that are much harder to reason with and that are much harder to avoid with signed intgers everywhere. All that is what makes me say that the whole "signed integers are easy, unsigned integers are hard" talk is bullshit.

They are a problem because there is no way to detect them with unsigned: the result of the multiplication is still positive. With signed, if there is an overflow, then the result of the multiplication is negative, and you can detect that easily.

Fair point, but then a negative size is meaningless and there are better ways to check overflow than that. Since we're talking about possible better designs for new languages, not necessarily C/C++, a new language could have a primitive to allow you to check wether the arithmetic operation overflowed, like the C/C++ intrinsics allowing to use jump if carry/overflow in x86, but builtin. That's the best solution to solve this particular problem imo, better have new primitives than reduce the expressivity of what we have now.

malloc would be able to detect the overflow at malloc

With new overflow checking primitives the caller can make that check.

But here again I don't think neither malloc nor unsigned integers are the real issue. Correct programs just won't be allocating that much data because this is more RAM that exist in the entire world and because how much memory a given program will be allocating for temporary or output data structures is correlated to the size of the input, and the input won't be that big. If an overflow happens here it's likely due to a bug somewhere else or because you're using unsanitized input data, input data who should have been rejected earlier because the values are not acceptable.

1

u/Tasty_Replacement_29 Bau May 08 '26

> If some programmers can't grasp what unsigned underflow/overflow there is no way in hell than they should fully understand all the signed overflow/underflow edge cases

You are right. (Even thought, it's quite easy: if the result of the addition has a different sign, it's overflow / underflow - this sign check is not available for unsigned). A bit simplified, there are two kinds of people: those that don't care and / or don't understand, and those that do care and understand. For those that don't care / understand, I am arguing the signed integer is less problematic, because overflow / underflow is extremely rare. With unsigned, it is quite common, because underflow is very close to a common case: 0.

> iterating in reverse is not that common

For Apache Jackrabbit (where I work on) I grepped for "for.*>= 0" and found 42 cases, and 2800 cases of "for.*= 0". Yes it is not common, but there are cases.

> bounds checking

This is true: there is one more case, you need to check for >= 0. But array bounds checking is typically done by the programming language. (this is about designs for new languages).

> a negative size is meaningless

No: it means there was an error. Basically, you have one bit to detect errors.

> with signed integers you're allowing possible out-of-bounds access

I don't follow why you would have it only with signed (if your language allows for out-of-bounds access).

> Integer overflows are a whole class of vulnerabilities that are much harder to reason with and that are much harder to avoid with signed intgers everywhere. All that is what makes me say that the whole "signed integers are easy, unsigned integers are hard" talk is bullshit.

I don't agree at all: with signed, it is easier to understand and prevent.

> a new language could have a primitive to allow you to check wether the arithmetic operation overflowed

Well there are ways to check that, it doesn't need to be integrated in the language. But using it everywhere, always, would slow down the language too much.

> the caller can make that check

The caller can make that check even now, but most callers are too lazy. The point is to have protection for the lazy developer.

> Correct programs

Well this is not about correct programs, it's about protection agains bugs, by _slightly_ incorrect programs.

1

u/EggplantExtra4946 May 08 '26

No: it means there was an error. Basically, you have one bit to detect errors.

So a negative size is not a valid size which is what I said.

I don't follow why you would have it only with signed (if your language allows for out-of-bounds access).

It's more a problem for 32bit sizes. If you happens to overflow an unsigned size/index it will wrap to 0 and stay in bounds, with a signed 32bit if you only have 31 bits available for the size (2GB) and if you overflow the sign in principle you should have an invalid size (negative) except that size/references are casted to unsigned so it could access 2GB of memory after the end of the buffer.

Well there are ways to check that, it doesn't need to be integrated in the language.

Using a conditional jump explcitly designed to check overflows is better and faster than other alternatives. I don't see why new languages should not take advantage of this cpu capability.

But using it everywhere, always, would slow down the language too much.

I didn't say that it all operations should have an implicit overflow check, I'm saying there should the primitive available to allow the user to manually check wether an overflow happened or not. Like this https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html but builtin.

I don't agree at all: with signed, it is easier to understand and prevent.

Bullshit. You yourself agreed that it's harder to understand and like I said, this is one the main classes of vulnerabilties and they happen all the time.

The point is to have protection for the lazy developer.

Sorry but that's not good enough, I would prefer to avoid programs written by lazy developpers and I won't allow them to touch to my code. Programming requires precision, writing correct programs even more so.

1

u/Tasty_Replacement_29 Bau May 08 '26

> So a negative size is not a valid size which is what I said.

Right. But with unsigned you have no way to detect the overflow / underflow, unless if you limit the maximum size (for example, require that the highest bit is zero or so).

> It's more a problem for 32bit sizes.

Yes, 32 bit array indexes... I'm not sure if I want in my language support such large arrays, or use 64-bit array indexing.

> Using a conditional jump explcitly designed to check overflows is better and faster than other alternatives.

Well... you already know that the array size is not negative. (In a memory-safe language). My language converts to C, and for the array-out-of-bounds check I can use

bool indexCheck(int x, int arrayLen) {
    return ((size_t) x) < ((size_t) arrayLen);
}