Advertisement
oaktree

Hardcore C Memory Management

Sep 6th, 2016
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. /*
  2.     Hardcore C Memory Management
  3.     9/6/16
  4.  
  5.     NOT SAFE. For god's sake: use glibc's malloc set.
  6.  
  7.     This is purely for learning purposes. 0/10 would
  8.     _never_ recommend for production, unless you're
  9.     planning on developing a memory management library.
  10.  
  11.     But, really. Are you a better C programmer than
  12.     the guys at the GNU Project?
  13. */
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <unistd.h>
  17. #include <string.h>
  18.  
  19. int main(void) {
  20.  
  21.     void *proc_break = sbrk(0);
  22.    
  23.     printf("Boundary: %p\n", proc_break);
  24.    
  25.     /* should increase by 4 bytes */
  26.     if (brk(proc_break + 4) < 0) {
  27.         perror("Couldn't Allocate Memory!!!\n");
  28.         exit(1);
  29.     }
  30.    
  31.     int *int_ptr = (int*)proc_break;
  32.     *int_ptr = 16;
  33.    
  34.     printf("This is stored at %p : %i\n", int_ptr, *int_ptr ); 
  35.     printf("Boundary: %p\n", sbrk(0));
  36.  
  37.     float *f_ptr = (float*)proc_break;
  38.     *f_ptr = 0.1;
  39.     printf("And now %p holds a float %.30f\n", f_ptr, *f_ptr);
  40.    
  41.     printf("Now I'm \"freeing\" that memory...\nsbrk(0) returns %p\n", sbrk(0));
  42.     if (brk(proc_break) < 0) {
  43.         perror("Couldn't Deallocate!!!\n");
  44.         exit(2);
  45.     }
  46.  
  47.     printf("But now it returns... %p\n", sbrk(0));
  48.     printf("Now let's allocate for 'hello world'\n");
  49.  
  50.     char *feed = "hello world"; // we're gonna copy this literal to the heap!
  51.  
  52.     if (brk(proc_break + strlen(feed)+1 ) < 0) {
  53.         perror("Couldn't Allocate Memory!!!\n");
  54.         exit(3);
  55.     }
  56.  
  57.     char *c_ptr = (char*)proc_break;
  58.    
  59.     for (int i = 0; i < strlen(feed) + 1; i++)
  60.         c_ptr[i] = feed[i];
  61.  
  62.     printf("c_ptr = %p and holds %s\n", c_ptr, c_ptr);
  63.  
  64.     brk(proc_break - 12);
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement