malloc.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. #define N_PTRS 100
  6. #define N_ALLOCS 100
  7. #define MAX_SIZE 0x10000
  8. #define random_size() (random()%MAX_SIZE)
  9. #define random_ptr() (random()%N_PTRS)
  10. int test1(void);
  11. int test2(void);
  12. int main(int argc, char *argv[])
  13. {
  14. return test1() + test2();
  15. }
  16. int test1(void)
  17. {
  18. void **ptrs;
  19. int i,j;
  20. int size;
  21. int ret = 0;
  22. srandom(0x19730929);
  23. ptrs = malloc(N_PTRS*sizeof(void *));
  24. for(i=0; i<N_PTRS; i++){
  25. if ((ptrs[i] = malloc(random_size())) == NULL) {
  26. printf("malloc random failed! %i\n", i);
  27. ++ret;
  28. }
  29. }
  30. for(i=0; i<N_ALLOCS; i++){
  31. j = random_ptr();
  32. free(ptrs[j]);
  33. size = random_size();
  34. ptrs[j] = malloc(size);
  35. if (!ptrs[j]) {
  36. printf("malloc failed! %d\n", i);
  37. ++ret;
  38. }
  39. memset(ptrs[j],0,size);
  40. }
  41. for(i=0; i<N_PTRS; i++){
  42. free(ptrs[i]);
  43. }
  44. return ret;
  45. }
  46. int test2(void)
  47. {
  48. void *ptr = NULL;
  49. int ret = 0;
  50. ptr = realloc(ptr,100);
  51. if (!ptr) {
  52. printf("couldn't realloc() a NULL pointer\n");
  53. ++ret;
  54. } else {
  55. free(ptr);
  56. }
  57. ptr = malloc(100);
  58. ptr = realloc(ptr, 0);
  59. if (ptr) {
  60. printf("realloc(,0) failed\n");
  61. ++ret;
  62. free(ptr);
  63. }
  64. return ret;
  65. }