#include /* "malloc" is defined in . */ #include /* This gives us "isprint". */ #include /* Safely show what is in memory. If the character is unprintable, print it like {AB}, where AB is the value in hexadecimal. */ static void hex_dump (char * r, int rl) { int i; for (i = 0; i < rl; i++) { if (isprint (r[i])) { printf ("%c", r[i]); } else { printf ("{%X}", (unsigned char) r[i]); } } printf ("\n"); } /* Fill "r" with random letters. */ static void randomly_fill (char * r, int rl) { int i; for (i = 0; i < rl - 1; i++) { r[i] = (random () % 26) + 'A'; } /* Put a zero byte at the end. */ r[rl - 1] = '\0'; } int main () { int j; for (j = 0; j < 4; j++) { /* Allocate here. */ char * r; /* r's length. */ int rl; /* Set "r" to 0 initially. */ r = 0; /* We want to test with various lengths of memory. */ rl = (j + 1) * 10; printf ("** Get %d bytes with malloc:\n", rl); /* Call malloc and get "rl" bytes of memory. */ r = malloc (rl); /* Test whether the call to malloc was successful. */ if (! r) { /* Print an error message to the standard error stream, "stderr". */ fprintf (stderr, "The call to malloc was not successful.\n"); /* EXIT_FAILURE and "exit" are defined in . The following tells the calling process that we hit a snag. */ exit (EXIT_FAILURE); } /* Inspect the memory we have got. */ printf ("Initially, the memory contains: "); hex_dump (r, rl); randomly_fill (r, rl); printf ("Filled up, the memory contains: "); hex_dump (r, rl); /* Thanks for the memory. */ free (r); } return 0; }