this post was submitted on 05 Aug 2024
266 points (94.0% liked)

Programmer Humor

19623 readers
3 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 1 year ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[โ€“] SpaceNoodle@lemmy.world 33 points 3 months ago (1 children)

I don't think I've ever explicitly gone four deep. Two is common enough, and three happens on some rare occasions, but four seems like sheer madness.

[โ€“] Ephera@lemmy.ml 11 points 3 months ago (1 children)

Dumb question, but when would you need two deep? Is it when you store a pointer as a field in a struct?

If so, isn't that a massive footgun, because the pointer might go invalid at any point? ๐Ÿซ 

[โ€“] SpaceNoodle@lemmy.world 20 points 3 months ago (1 children)

Pointers to arrays or arrays of pointers are common examples.

Your pointers won't just magically become invalid. You gotta fuck 'em up first.

[โ€“] Ephera@lemmy.ml 4 points 3 months ago (1 children)

Ah, you mean "pointers to arrays", because arrays are themselves just pointers in C/C++. That one still feels like it shouldn't be needed in practice, because you already got a pointer, why can't you use that directly? But yeah, I have no practical experience with C/C++.

And you do gotta fuck 'em up, as in free what they're pointing to before you free the struct/array containing the pointers.
But when you do stick them into a struct/array, that often means you want to move them out of the scope with the malloc and potentially store them, too.
At that point, surely, it becomes rather difficult for your whole team to know or track down when it's legal to free that.

I only know from Rust that if you want to store a pointer/reference in a struct, it makes you specify the lifetime of that struct, which has to be greater or equal to the lifetime of the thing the pointer is pointing to. Hairy stuff. We've basically told the Rust newbies on our team to just not store pointers in structs and that's working rather alright.

[โ€“] SpaceNoodle@lemmy.world 4 points 3 months ago

Arrays may be implemented as pointers on C, but the distinction is on how they are used, which is why I used the verbiage I did.

What if you need to modify a reference to a pointer, e.g. change the value of a value referencing a certain place in an array? strtol(), for example, uses a pointer to a pointer to a char to indicate the end of the parsed portion of the input string.

Major codebases performing high-level operations on data that's shared in barely trackable scopes certainly aren't best implemented in C. It's still the language of choice for low-level code, especially on embedded systems, where allocations are not taken lightly.