An example of using malloc
This is an example C program demonstrating the use of
malloc
.
#include <stdio.h> /* "malloc" is defined in <stdlib.h>. */ #include <stdlib.h> /* This gives us "isprint". */ #include <ctype.h> /* 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 <stdlib.h>. 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; }
The output of the example looks like this:
** Get 10 bytes with malloc: Initially, the memory contains: {0}{0}{0}{0}{0}{0}{0}{0}{0}{0} Filled up, the memory contains: NWLRBBMQB{0} ** Get 20 bytes with malloc: Initially, the memory contains: {FF}{FF}{FF}{FF}{FF}{FF}{FF}{FF}{FF}{FF}{FF}{1F}{FF}{0}{0}{0}NWLR Filled up, the memory contains: HCDARZOWKKYHIDDQSCD{0} ** Get 30 bytes with malloc: Initially, the memory contains: HCDARZOWKKYHIDDQSCD{0}BBMQB{0}{0}{0}{0}{0} Filled up, the memory contains: XRJMOWFRXSJYBLDBEFSARCBYNECDY{0} ** Get 40 bytes with malloc: Initially, the memory contains: {0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0}{0} Filled up, the memory contains: GGXXPKLORELLNMPAPQFWKHOPKMCOQHNWNKUEWHS{0}
The memory may contain anything initially. For example, the memory may
be recycled from a previous call, or it may contain all zeros. To
guarantee that the memory is set to zeros initially, use
calloc
rather than malloc
.
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer