#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int argc, char * argv[ ] ) {
char * char_ptr; // a char pointer
int * int_ptr; // an integer pointer
int mem_size;
if ( argc < 2 ) // if there aren't commandline arguments,
mem_size = 50 ; // use 50 as the default value..
else
mem_size
= atoi ( argv
[ 1 ] ) ;
printf ( "\t [+] allocating %d bytes of memory on the heap for char_ptr\n " , mem_size
) ; char_ptr
= ( char * ) malloc ( mem_size
) ; // allocating heap memory
if ( char_ptr == NULL) { // error checking, in case malloc() fails
fprintf ( stderr
, "Error: could not allocate heap memory.\n " ) ; }
strcpy ( char_ptr
, "This is memory is located on the heap." ) ; printf ( "char_ptr (%p) --> '%s'\n " , char_ptr
, char_ptr
) ;
printf ( "\t [+] allocating 12 bytes of memory on the heap for int_ptr\n " ) ; int_ptr
= ( int * ) malloc ( 12 ) ; // allocated heap memory again
if ( int_ptr == NULL) { // error checking, in case malloc() fails
fprintf ( stderr
, "Error: could not allocate heap memory.\n " ) ; }
* int_ptr = 31337 ; // put the value of 31337 where int_ptr is pointing
printf ( "int_ptr (%p) --> %d\n " , int_ptr
, * int_ptr
) ;
printf ( "\t [-] freeing char_ptr's heap memory...\n " ) ; free ( char_ptr
) ; // freeing heap memory
printf ( "\t [+] allocating another 15 bytes for char_ptr\n " ) ; char_ptr
= ( char * ) malloc ( 15 ) ; // allocating more heap memory
if ( char_ptr == NULL) { // error checking, in case malloc() fails
fprintf ( stderr
, "Error: could not allocate heap memory.\n " ) ; }
strcpy ( char_ptr
, "new memory" ) ; printf ( "char_ptr (%p) --> '%s'\n " , char_ptr
, char_ptr
) ;
printf ( "\t [-] freeing int_ptr's heap memory...\n " ) ; free ( int_ptr
) ; // freeing heap memory printf ( "\t [-] freeing char_ptr's heap memory...\n " ) ; free ( char_ptr
) ; // freeing the other block of heap memory }
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHN0cmluZy5oPgoKaW50IG1haW4oaW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