#include int main() { char s[] = "Hello World!"; char *t = s; int *badptr = NULL; // We set character pointer 't' to point to the start of // statically-allocated string 's'. This loop walks // down the string, printing the value of the pointer, // and three different representations of the byte // pointed to. Loop conveniently stops when we reach // the null terminator, '\0'. do { printf("(0x%08X): %c %3d 0x%X\n", t, *t, *t, *t); } while (*(t++) != 0); printf("\n\n"); // Here is where things start to go wrong. Badptr is for // integers, not characters. Because pointer arithmetic // is scaled according to the size of the type pointed to, // badptr will loop through memory 4 bytes at a time. badptr = (int *)s; // This loop interprets the harmless, peace-loving characters // in our string as 32-bit integers, (on x86 processors,) // and will not be stopped by the 8-bit null terminator // character. // Don't try this at home, kids. do { printf("(0x%08X): %12d 0x%08X\n", badptr, *badptr, *badptr); } while (*badptr++); }