Skip to content

Pointer Walk

You'll write your own string functions with nothing but pointers, print the addresses to see where things live, and draw it all on paper.

About

A pointer is just a number that happens to be an address, and the quickest way to believe that is to print one. You'll rewrite strlen, strcpy and a string reverse using pointer arithmetic alone, with no library calls, and then draw the memory on paper so the picture in your head matches what the machine does. The trap for every beginner is forgetting the zero byte at the end of a string, so you'll remove it on purpose and watch what happens. Rust folks can do the same with raw pointers inside unsafe blocks, but C makes the lesson plainer.

At a glance

Per requirement
15 XP
Completion bonus
75 XP
Requirements
5
Takes
One evening
Skill level
Beginner (done it a few times)
Cost
Free
Supplies
You need some
Where
At home
Other people
On your own

Requirements

  1. 1
    Print the address and size of a char, an int, a pointer and an array. Use printf with %p for addresses and sizeof for sizes, and print the address of a local variable, a global, and a block from malloc. Notice which addresses sit near each other and which are far apart, because that's the stack, the data segment and the heap. Take a screenshot of the output with a note of which was which. Photo
  2. 2
    Write your own string length and string copy using pointers, with no library calls. Walk the bytes with a pointer until you hit the zero, counting as you go. For the copy, keep two pointers and advance both. Test them against the real strlen and strcpy on a dozen strings, including an empty one. Take a screenshot of the functions and the test passing. Photo
  3. 3
    Reverse a string in place with two pointers and no second buffer. One pointer starts at the front and one at the last character, and you swap and move them toward each other until they meet. Try it on an odd length string, an even length string, and a single character. Take a screenshot of the function and the output for all three. Photo
  4. 4
    Drop the terminating zero on purpose and show what your string length does to it. Make a char array with no room for the zero, as in char s[5] = "hello", and call your strlen on it. It reads past the end into whatever is next in memory, which is the bug behind a long list of security advisories. Note what number came back and why it was wrong. Take a screenshot of the run and your note. Photo
  5. 5
    Draw the memory for your reverse function on paper, box by box, with addresses. Draw the array as a row of boxes with one address under each, then draw the two pointers as arrows and show them after each swap. If the drawing and the program disagree, the drawing is wrong, so run the program under the debugger and fix the drawing. Take a photo of the page. Photo