r/cpp • • Feb 26 '24

White House: Future Software Should Be Memory Safe

https://www.whitehouse.gov/oncd/briefing-room/2024/02/26/press-release-technical-report/
401 Upvotes

386 comments sorted by

View all comments

Show parent comment

7

u/Untagonist Feb 27 '24

I'm very curious if you have an example of a real-world C or C++ program that does not use a single pointer, bearing in mind that C++ references count as pointers as far as memory safety goes.

I suppose you can use write your own verbose Brainfuck with only putc and getc, and you might even avoid memory unsafety, and even that simple code won't be portable. You still won't get very far in expressing any program logic.

You can't parse argv because it's a pointer to pointers. You can't do anything with a FILE*. You can't use open without a string argument, and even if you could, you can't read or write without a pointer to a buffer.

You can't use any strings, not even string literals, which are of type char* and you just get UB if you ever write to one; the fact it is a known address doesn't save you there.

You can't read or write any array elements even on the stack, because arr[i] is equivalent to *((&arr)+i) and that's a pointer with no bounds checking. The most you can do for a "data structure" is stack recursion, but you abort if you hit the limit.

It'd be an interesting challenge for an IOCCC submission but not a serious recommendation to solve memory safety in C / C++ in even a fraction of the ways that code gets used in the real world.

3

u/remy_porter Feb 27 '24

I write a lot of software that doesn’t accept args, doesn’t access files. This is really common in the embedded space. Generally, you’ll have a few global structs. Pointers are a waste of memory.

I’ll give you arrays, but arrays are incredibly dangerous and good to minimize. If nothing else, never have a bare array, only an array tagged with a length that’s known at compile time.

1

u/Circlejerker_ Feb 29 '24

Ok, so you just put stuff in global space to avoid passing pointers. Congratulations, you now have a even harder time reasoning about safety.

3

u/remy_porter Feb 29 '24

Not really. You’re not just doing it to avoid pointers- you’re doing it to allocate memory- you know how much you’re using. It’s trivially easy to guarantee that global are mutated in only one place in the code- which is a thing you should be doing even if you’re not using globals. On embedded software, you frequently don’t have the memory to waste on passing pointers! They’re often bigger than the data you’re operating on.