44 points · by dce · 13y ago · 75 comments
From what I understand in formal CS courses, you learn from the bottom up, but learning from the top down was much more enlightening for me.
I also learned how data structure libraries can be separated from user code (when learning C in class we usually created ad-hoc data structures heavily coupled with the calling code).
Exactly. Not only that you but I had started to appreciate the scripting language (Python) more because I see much it does for you. I knew that before but actually seeing how one would have to handle reference counting, error handling it is nice to go back to Python.
To those versed in C, is the tutorial linked in the original article a recommended one?
Disclaimer: I already knew C fairly well and decided to go through LCTHW to see if I could pick up any hidden gems; might differ for someone with little to no experience.
unique_ptr<>, scoped_ptr<>, and shared_ptr<> all say different things about heap memory lifetime, and those make it easier to maintain your grasp on what you're asking the computer to do.
Like many things in C++, you can do that in C too (e.g. by using a variant of Hungarian notation). But the important thing is to do it.
Rust's memory management works similarly to what you describe in C++[0], but things like unique_ptr, et al. are baked into the syntax and compiler. -- It's basically syntactic sugar for memory semantics.
Coming from a background of GC'd languages (Java, Go, and Ruby) these different allocation semantics were Very Hard(TM) for me to understand at first. I kept battling w/ the type checker, throwing different pointer types at it until the example compiled. (Rust's compiler is _very_ intelligent, w/o using "unsafe" code, you basically cannot have a "use after free" condition in Rust. -- It will not compile.)
As the parent points out: I've never really spent any length of time _understanding_ the allocations I'm asking a computer to make. I just generate things, they become garbage, and the runtime cleans it up eventually.
Once Rust "clicked" for me, I realized something: I know the lifetime of _every single variable_ in this piece of code.
I know when it's allocated, where it's allocated, and when it gets freed.
The reason it was so hard for me to initially grok Rust was because I'm _not used to reasoning_ about memory allocation.
Once I understood the semantics though, it was as though I had an _entirely new_ level of abstraction at my fingertips.
These semantics are definitely some powerful stuff, and I'm very glad I'm taking the time to try and understand them.
[0]: http://pcwalton.github.com/blog/2013/03/18/an-overview-of-me...
Suddenly you have distributed knowledge across team members with various skill levels and producing memory leaks is very easy.
Nowadays automatic memory management in the form of GC or reference counting is the way to go.
https://www.youtube.com/watch?v=IkyWCOUY8V4
The terminology may not be completely accurate (although I did try very hard to not say anything incorrect), but I honestly think it does a good job of showing you how to actually use pointers. I know the resident C experts will probably find something wrong, but I've received tons of comments and emails from people saying they finally "get it". It's something I'm proud of.
I doubt that anyone struggles to understand pointers, they/we struggle to understand the implementation of pointers in C, in some cases. If you want to explain pointers, to people from a object oriented programming background, you might start by comparing points to "by reference" and "by value".
My issue has always be why I would care about the memory address of a variable, rather than getting the value as the default behavior, but that might be why I suck a C.
That's the easy part. Not many people (if any) struggle to understand that. It's all the consequences of that, and they way it interplays with various C features, that get people confused.
I find that its often badly taught using truly awful analogies that don't help and are often actively unhelpful as soon as you step outside the very narrow boundaries of the analogy. A simple and easy thing, badly taught, becomes difficult.
Many new programmers seem to warm up to Java "references" just fine, and they have mostly the same semantics of C pointers.
Maybe it's because passing by value is conceptually harder to grasp than passing by reference, and in C you must understand both in order to use pointers?
"Function pointers — It was interesting to me to see that such a low-level language contained functional programming concepts."
If you started from assembly and worked up, this looks very different, because at that very low level, functions and data look the same too. (Just like Lisp).
The punchline: "Since calls to known procedures are just gotos that pass arguments, lifted lambda expressions are just assembly language labels that have been augmented by a list of symbolic names for the registers that are live at that label."
You aren't going to have the expressiveness that a Lisp provides available to you, but self-modifying code and macros assemblers are common in some assembly programming scenes. Anything to save a few bytes or cycles. I'm a little rusty, but here's a basic example off the top of my head (sorry, wall of text incoming):
Functional programmers are familiar with the concept of "map," an operation that applies a function to every element in a list or what have you. Let's say I'm programming in 6502 assembly, and I have a little function that adds an amount to every byte in a page (or every byte in some particular 256 bytes). Let's say you also want a similar function that instead multiplies each byte by two (just a single left shift), or masks some bits off with a bitwise AND, or whatever. It would look something like this:
store zero in X register, add constant to the memory at the address (some constant address + value in X register), increment X, branch back to the adding part if the zero flag is not set (ie, loop until X overflows to 0), then return to wherever we called this function from.
You could write a handful of these almost identical subroutines, with the only real difference being the single opcode that reads, modifies, and rewrites each byte... or you could just rewrite the opcode at runtime!
Now, your add-to-page, multiply-page, mask-out-page, and any similar functions all share a little block of code that you can think of as "their map," and the actual functions you call initially could look something like this:
Write the constant for the relevant opcode to the instruction in map you want to replace ($7D for ADC absolute,X on the 6502), and jump to the map subroutine.
That's a bit of a contrived example, but in a routine with a more complicated access pattern, it might really make a difference in byte savings: Imagine a routine that clips offscreen entities in a game, that calculates something like "if their X coordinate is below or above some value, they disappear for now. If their Y coordinate is below some value, they fell into a pit and died." You could reuse a lot of the general logic for checking the left edge of the screen for the other two edges, just by rewriting a constant and instruction or two.
A perhaps more readily useful example is rewriting "constant" addresses. How would we rewrite our above "map" routine to modify arbitrary pages, and not just one in particular? We could store the address of the page we want to modify in memory, and use an indirect addressing mode for add. Indirect addressing modes of instructions do something like this: Load two bytes from some address in memory, and treat that as the address we want to operate on. Problem is, this indirect address mode adds two cycles to every operation we perform when compared to the original constant-address map. Suddenly, we're wasting over 500 cycles per map!
The solution is instead to treat the "constant" address in the instruction stream of the map routine as your address variable. Just rewrite those two bytes during your "function prologue," and voila, you have a general-purpose map routine that only uses half-a-dozen cycles or so more than one that only worked on a certain page.
The part I've been leaving out is using assembler macros to automate a lot of this stuff for you. Again, I'm rusty, and I never got all that experienced in writing macros, but someone could very easily write themself a macro (if they're using a powerful macro assembler, like ca65) that takes a single argument, the instruction you want to execute in your map, and generates for that stub subroutine that replaces the opcode for them. I found simpler macros to be more useful in everyday code, though: you make a macro that fills in a gap in the 6502's instruction set, like performing arithmetic between the accumulator and index registers, or basic 16-bit arithmetic, and from then on, you can pretend that the CPU had those instructions all along.
I may have only used these techniques for shaving bytes and cycles off of straightforward routines, but in some ways, going from writing 6502 assembler to writing C, Lua, and JavaScript actually feels like a step back in terms of expressiveness, even if they are certainly more productive languages in actuality, and first-class functions/function pointers cover much of the most practical (and least dangerous) use-cases for self-modifying code. I suppose I won't get that feeling back until I set some time aside to really learn a Lisp.
Back in the old days, before memory protection, we used to do all kinds of code-as-data-as-code tricks. I remember dynamically generating trampoline functions that effectively did partial application. I'd write a little stub of assembly code that would push a bunch of literal zeros onto a stack and then jump to zero; when I wanted to use it, I'd copy it, poke actual values into the literals, and then pass it along as a zero-parameters function pointer.
You don't change the language syntax; that doesn't really make sense in assembly world. It's more that assembly code lives in a world of bytes and pointers, and is itself very directly composed of bytes and pointers, and so it's as easy to use the same bytes-and-pointers concepts on code as it is on data.
This style still exists on microcontrollers, where there is generally no operating system. Instead, your compiler produces an image which you flash onto the controller chip. The controller has some startup sequence which jumps to some address in flash and runs. The chip's subsystems are controlled by registers located at specific addresses; in order to drive such a device you have to know how its address space is laid out, where your code is placed in it, and how your code interacts with the different types of memory and registers located in the address space.
But as long as we're picking nits --
It is of course completely possible to create executable code during runtime, using assembler. Often not advisable. (Recall the punch line of: http://www.cs.utah.edu/~elb/folklore/mel.html)
I was reading some old Apple II assembly last year, and one very common way to do loops is like this:
1. Is 10 equal to 0?
2. If so, go to step 6.
3. Do a bunch of stuff.
4. Decrement the first number written in step 1.
5. Go to step 1.
6. Rest of program.
Variables are declared like this:
name : type;
for example, here is an integer i and a pointer to an integer p: i : integer;
p : ^integer;
^ reads like "pointer to" here.If you want to point p to i's address:
p := @i;
@ reads like "address of" here. "at" also makes sense. By the way := is the assignment operator.And if you want to assign a value to what a pointer points to (in other words, deference it), you can:
p^ := 42;
The equivalent C would be: int i;
int *p;
p = &i;
*p = 42;
I guess it's not that different.Well if you consider that the computer is still less than a century old, 15 years is a long time in the computer world.
"For Windows users I'll show you how to get a basic Ubuntu Linux system up and running in a virtual machine so that you can still do all of my exercises, but avoid all the painful Windows installation problems."
A bootable Ubuntu USB stick with persistent storage might be easier to get started with? Can be created from a Live CD.
Interesting idea.
Things that annoy me about Ubuntu dual boot
* My Wacom tablet is terribly hard to configure on Ubuntu. * Flash support seems to be hit or miss in terms of out of the box functionality. Sometimes it works right when you install chromium, sometimes it doesn't * Windows weird partitioning. Windows will only let you have 1 or 2 of these special types of partitions on your HDD, and I somehow maxed out that partition count and couldn't fix it. It was very difficult to work with.
I was thinking more of a group of people meeting to work through the Learn C the hard way book, perhaps in a coffee bar or something, bringing their own laptops. A bootable stick might make a C environment more accessible to them.
The puredyne project produced a bootable linux specifically to provide a common environment for training in audio production. Seemed to work for them.
But I've heard Vagrant is good for use cases like yours, though I haven't personally used it.
That sounds like a fun activity by the way, have fun with that :)
Also, C++ is arguably faster than C (for the effort put in) and Objective C is a strict superset. Saying either calls into C for performance reasons is pretty silly and doesn't make any sense.