正在加载视频...
视频加载失败
To build a generic swap in C, pass the size explicitly, create a temporary byte buffer, then use memcpy three times to rotate the bit patterns. VLA char buffer[size] is a GCC thing, for a more portable version malloc the temp and free it. Stanford CS107, lecture 4
31 条评论

memcpy swap is classic. malloc overhead though.

Why allocate memory? Use 3 xor operations

The size argument should have size_t type as it does in memcpy. If you use a sized int, you're limiting the range of the size argument and you arguably need to check for negatives.

who is this lecturer? He’s great

Yeah, this code uses VLA, a feature that is frowned upon.

Or you could use XOR 3 times

👀 those were the good old days 🥹

This doesn't prevent using different types of pointers, right? So it's a clever way of allowing users to attempt to overwrite data 🤔

I watched the entire 6 minutes at normal speed! Really interesting. Covers a lot of topics in a great way.

Or the triple XOR

This guy could be a fantastic vibe coder.

Thanks for the lesson — in loving my Rust more!

This is like crack

Vp1/vp2 are the stupidest variable names I've seen in a long time.

If nothing else, I would typedef the char, but it is just ugly imo to use a char buffer for data that you don’t know to be characters.

Should have used unsigned char instead of char?

VLA blows up if size > stack, and stack is surprisingly tiny. But not using VLA is trivial here. Even then, why bother with all that? For register-sized swaps, it's much cheaper to do inline, that likely avoids memory access and/or results in a noop. For big swaps, no need to copy data around, it is simply enough to swap pointers around one level up. You know, kinda the point of pointers is to abstract data location.

raw low level

Before vibe coding, people should understand that

XOR ftw

Any with extra steps

Any alignment concerns with that byte buffer?

Can't we just use Claude Code to do this instead?

Void comment incoming

I watched these in my college times great lectures

Use alloca. Skip the free and gain performance.

I have to admit that I didn’t go to college for CS it’s self taught but isn’t this like lesson 1? Like I am slightly concerned that people find this to be new information

that's exactly how i've been doing swaps in my own projects but i think it's worth noting that with clang you don't need to use memcpy at all, just a simple pointer arithmetic will do

🤔🤔

VoidSwap sounds like tinder for goth couples

Brings me back

