Skip to content
0:00 / 0:00

#unsigned#types#cppcon

CppCon 2016: Jon Kalb “unsigned: A Guideline for Better Code"

CppCon

189K subscribers • 101 videos on Hallway • Conference channel

YouTube
  • Recommended by 2 people: 1 on Lobsters and 1 in engineering communities.
  • Presented by Jon Kalb
  • Linked in the descriptioncppcon/cppcon2016
  • An opinion. It argues one side of a question engineers disagree on.

Intermediate. Assumes working knowledge.

20K views10 years ago2 recommendations

Programming languagesSoftware designC++Design patterns

Jon Kalb delivers a lightning talk arguing against the common use of unsigned types in C++ except for bit patterns.

CppCon.org — Presentation Slides, PDFs, Source Code and other presenter materials are available at: github.com/cppcon/cppcon2016 — Lightning Talk — Videos Filmed & Edited by Bash Films: BashFilms.com Work at Hudson River Trading (HRT): tinyurl.com/safxfctf

Why it's here

2 people recommend this

What people say. Recommended as a classic, humorous lightning talk on the pitfalls of mixing signed and unsigned integers in C++.

u/Tasty_Replacement_29Bauin r/ProgrammingLanguages • Recommends

On “Unsigned Sizes: A Five Year Mistake”

There are two related presentations: * [video , at minute 13, Bjarne Stroustrup says use unsigned only for bit patterns, and don't mix signed and unsigned. (To be honest, you can use signed for bit patterns as well, just that you need to shift unsigned.) * link to this video - which is quite funny.

inactive-useron Lobsters • Recommends

unsigned: A Guideline for Better Code (2016)

u/skeetoin r/C_Programming • Mentions

On “How to learn and write secure C code from the start?”

First step, enable sanitizers when you build for all testing and development: $ cc -g3 -fsanitize=address,undefined ... These place low-to-moderate cost checks throughout your program so that you can catch mistakes sooner. Platform support varies, but with GCC and Clang, Undefined Behavior Sanitizer is available in some form on all platforms. They don't have the best defaults, so adjust those as well: export ASAN_OPTIONS=abort_on_error=1:halt_on_error=1:detect_stack_use_after_return=1 export UBSAN_OPTIONS=abort_on_error=1:halt_on_error=1 The options make it a little more thorough, and errors will trap in your debugger so that you can investigate when they occur. Speaking of w…

u/skeetoin r/C_Programming • Mentions

On “Is it good practice to use uints in never-negative for loops?”

Negatives being out of a variable's expected range is not a good reason to use unsigned arithmetic. Unsigned operations have a large discontinuity next to zero and are unintuitive, making them error prone. An off-by-one causing what would be a negative result becoming huge value is a common source of bugs. A good rule of thumb is to [use signed types for quantities], and only use unsigned types when you specifically need their range (octets, `uintptr_t`), or you want their specific unsigned semantics (hash functions, cryptography).

u/Goobyalusin r/C_Programming • Mentions

On “what's the right datatype to store an array length?”

Here are a couple 2016 CppCon talks arguing for using the signed types. Idk if the debate is still raging or there is a consensus these days on how to deal with these issues. (57m talk on UB by Chandler Carruth) link to this video (6m talk on unsigned by Jon Kalb) link to this video

u/skeetoin r/C_Programming • Mentions

On “ptrdiff_t vs size_t”

Adding to this: CppCon 2016: Jon Kalb “unsigned: A Guideline for Better Code" > The length should always be positive. Intermediate length values may not necessarily be positive, nor potential lengths as part of a check. For example, reverse iteration: for (ptrdiff_t i = len - 1; i >= 0; i--) { ... } This index needs to support negative values despite not actually subscripting with negative. If `len` is unsigned and possibly zero, then `len - 1` probably isn't the result you expect it is. Yes, there are ways to work around this using unsigned operands, but the workarounds are required because unsigned has the wrong semantics for sizes and similar arithmetic. Or another: if (a.…

u/skeetoin r/C_Programming • Mentions

On “I made a sokoban clone”

Slick game! The 3D effect and animations are nice, and you accomplished more with 1.1KLoC than I would have expected. Though the 3D view, along with destination tiles hidden underneath boxes, makes it difficult to see what's going on. Other Sukoban games typically display boxes differently when they're on a destination, which makes everything so much clearer. That probably wouldn't be difficult to change. Curiously you managed to hit a buffer overflow in the raylib OBJ parser. It happens when models have an empty group name, so I just added names: --- a/assets/models/box/box1.vox.obj +++ b/assets/models/box/box1.vox.obj @@ -3,3 +3,3 @@ # group -o +o box…

u/skeetoin r/C_Programming • Mentions

On “Fun with -fsanitize=undefined and Picolibc”

Great overview! All software in actual use should be tested at least this well. > The management structure appears just before that in memory; computing > the address of which appears to be undefined behavior to the compiler. > The only fix I could do here was to disable the sanitizer in functions > doing these computations -- the sanitizer was mis-detecting correct code > and it doesn't provide a way to skip checks on a per-operator basis. > > ... > > Null pointer plus or minus zero. C says that any arithmetic with the > NULL pointer is undefined, even when the value being added or subtracted > is zero. The fix here was to create a macro, enabled only when the > sanitizer is enabled, whi…

u/skeetoin r/C_Programming • Mentions

On “C Code for Exif data”

Interesting project! These array members are quite excessive: typedef struct { // ... char locINT_MAX; //store end location result } t_res; typedef struct { unsigned char bufferINT_MAX; // ... } t_data; This would never work on a 32-bit system, and it even won't work on some 64-bit hosts. The program should be more dynamic and flexible. `read_file` returns a `bool` to indicate if it found anything, but this result is ignored and it marches forward printing garbage. This loop makes the program crash on any input under 10 bytes: for (size_t i = 0; i < bytesRead - 10; i++) That's because the subtraction overfl…

u/skeetoin r/C_Programming • Mentions

On “Here's a reusable function to remove duplicate elements in an array while maintaining the original sort order without quadratic time complexity.”

If the left side of `inputi % *count` was hashed first to uniformly distribute the inputs, and the probe step size in `(position + 1) % *count` was derived from a hash, then you'd essentially have what I call a mask-step-index hash table, which fits this problem well. I'd adjust the interface to return the new length instead of an "inout" parameter. If they weren't already bundled together in a struct, also put the length after the pointer, which is the typical order. Finally, rather than make the caller allocate something specific, I'd have them pass a scratch arena so that the function can allocate whatever it needs, freeing the caller of that concern: int32_t remove_duplicates(int…

u/skeetoin r/C_Programming • Mentions

On “Advice for a new professor teaching C”

Here's my article on this very topic: My favorite C compiler flags during development. If I were to teach a course in C now, the default set of flags I'd have students use is: -Wall -Wextra -Wconversion -g3 -fsanitize=address,undefined `-Wall -Wextra` is obvious. `-Wconversion` is uncommon, but it's the best tool for catching accidental integer truncation — something that's a bit too easy in C. (MSVC offers a UBSan-like run-time truncation check, which I'd *love* to have in GCC.) I expect this warning would develop student's thoughtfulness about numeric ranges — something that even advanced C programmers don't consider nearly often enough. It's a skill that goes beyond C and C++. Like…

u/Goobyalusin r/C_Programming • Mentions

On “Is it good practice to use uints in never-negative for loops?”

link to this video

u/skeetoin r/C_Programming • Mentions

On “Tips on my Gale-Shapley algorithm implementation in C”

> why use `enum { MAXN = 32 }` and not `#define MAXN 32`? A `#define` is a dumb textual replacement above the language in the preprocessor, made without regard to context, including scope. `enum` creates proper integral constants in the language and scoped. Cleaner than preprocessor definitions, so I prefer them when possible. I picked this up from u/N-R-K. The `const` qualifier really means "read only" not "constant" and so generally isn't useful for defining constants. That's why C++ had to invent a whole new concept of constant, `constexpr`, which has just recently made its way into C. > But what is `align`? Every type has a minimum alignment, and its address must be a multiple of thi…

u/skeetoin r/C_Programming • Mentions

On “I made a library for string utilities”

> IMO you should use a `size_t` for length. `ptrdiff_t` is the result of > subtracting one pointer from another, and is only guaranteed to be at > least 16-bits. Sizes and subscripts should be signed. Like null terminated strings, unsigned `size_t` is a giant, historical wart in the C language because [unsigned arithmetic is hazardous] and a common source of bugs. (I find such defects in people's projects around here all the time.) Better to avoid `size_t` as much as possible. Subtracting pointers is the opposite of subscription, so `ptrdiff_t` is the most natural type for subscripts. It's also always large enough for both sizes and subscripts.

u/skeetoin r/C_Programming • Mentions

On “Bitmap Decoder Segmentation Fault”

> How exactly did you find the size of what it's writing? I began with a quick scan through your code, noticing both the VLAs and potential integer overflows. VLAs are a beginner trap, and my initial suspected you were simply blowing the stack with a large image. I didn't notice the `* 20` was wrong because that's not easy to see at a glance from the format string. Then I generated a relatively small image to check if it was something else (via ImageMagick): $ convert -size 100x100 xc:#ff00ff example.bmp $ gdb --args ./a.out example.bmp (gdb) r ERROR: AddressSanitizer: dynamic-stack-buffer-overflow on ... WRITE of size 23 at ... ... #2 0x563096a99554 in…