fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main(int argc, char *argv[]) {
  6. char *char_ptr; // a char pointer
  7. int *int_ptr; // an integer pointer
  8. int mem_size;
  9.  
  10. if (argc < 2) // if there aren't commandline arguments,
  11. mem_size = 50; // use 50 as the default value..
  12. else
  13. mem_size = atoi(argv[1]);
  14.  
  15. printf("\t[+] allocating %d bytes of memory on the heap for char_ptr\n", mem_size);
  16. char_ptr = (char *) malloc(mem_size); // allocating heap memory
  17.  
  18. if(char_ptr == NULL) { // error checking, in case malloc() fails
  19. fprintf(stderr, "Error: could not allocate heap memory.\n");
  20. exit(-1);
  21. }
  22.  
  23. strcpy(char_ptr, "This is memory is located on the heap.");
  24. printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
  25.  
  26. printf("\t[+] allocating 12 bytes of memory on the heap for int_ptr\n");
  27. int_ptr = (int *) malloc(12); // allocated heap memory again
  28.  
  29. if(int_ptr == NULL) { // error checking, in case malloc() fails
  30. fprintf(stderr, "Error: could not allocate heap memory.\n");
  31. exit(-1);
  32. }
  33.  
  34. *int_ptr = 31337; // put the value of 31337 where int_ptr is pointing
  35. printf("int_ptr (%p) --> %d\n", int_ptr, *int_ptr);
  36.  
  37.  
  38. printf("\t[-] freeing char_ptr's heap memory...\n");
  39. free(char_ptr); // freeing heap memory
  40.  
  41. printf("\t[+] allocating another 15 bytes for char_ptr\n");
  42. char_ptr = (char *) malloc(15); // allocating more heap memory
  43.  
  44. if(char_ptr == NULL) { // error checking, in case malloc() fails
  45. fprintf(stderr, "Error: could not allocate heap memory.\n");
  46. exit(-1);
  47. }
  48.  
  49. strcpy(char_ptr, "new memory");
  50. printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
  51.  
  52. printf("\t[-] freeing int_ptr's heap memory...\n");
  53. free(int_ptr); // freeing heap memory
  54. printf("\t[-] freeing char_ptr's heap memory...\n");
  55. free(char_ptr); // freeing the other block of heap memory
  56. }
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
	[+] allocating 50 bytes of memory on the heap for char_ptr
char_ptr (0x9886008) --> 'This is memory is located on the heap.'
	[+] allocating 12 bytes of memory on the heap for int_ptr
int_ptr (0x9886040) --> 31337
	[-] freeing char_ptr's heap memory...
	[+] allocating another 15 bytes for char_ptr
char_ptr (0x9886050) --> 'new memory'
	[-] freeing int_ptr's heap memory...
	[-] freeing char_ptr's heap memory...