malloc() memory allocation handling


/ Published in: C
Save to your folder(s)

In C, you have to manage your own program's memory. So if you allocate memory using malloc() you should not forget to free() it when no longer required.

You should also make sure if there is available memory in your system to allocate.


Copy this code and paste it in your HTML
  1. Add this function:
  2.  
  3. #include <stdlib.h>
  4. #define MALLOC_ERROR -1
  5. ...
  6. static void *checked_malloc(const size_t size)
  7. {
  8. void *data;
  9.  
  10. data = malloc(size);
  11. if (data == NULL)
  12. {
  13. fprintf(stderr, "\nOut of memory.\n");
  14. fflush(stderr);
  15. exit(MALLOC_ERROR);
  16. }
  17.  
  18. return data;
  19. }
  20. (can be improved with calloc() usage and realloc())
  21.  
  22. Then, invoke the method with:
  23.  
  24. char *new_data;
  25. size_t whatever_u_need = 20;
  26. new_data = checked_malloc(whatever_u_need);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.