testmalloc.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. struct list {
  5. struct list *next;
  6. };
  7. int main(void)
  8. {
  9. int z=999;
  10. int *y=&z;
  11. int *x=NULL;
  12. struct list *save;
  13. struct list *lp;
  14. int i;
  15. printf("pointer to x is %p\n", x);
  16. printf("pointer to y is %p\n", y);
  17. x=malloc(sizeof(int)*2000);
  18. printf("pointer to x is %p\n", x);
  19. y=malloc(sizeof(int)*100);
  20. printf("pointer to y is %p\n", y);
  21. free(x);
  22. free(y);
  23. printf("about to free(0)\n");
  24. free(0);
  25. x=malloc(13);
  26. printf("x = %p\n", x);
  27. memcpy(x, "Small string", 13);
  28. printf("0x%p test string1: %s\n", x, (char *)x);
  29. y = realloc(x, 36);
  30. printf("0x%p test string1: %s\n", y, (char *)y);
  31. memcpy(y, "********** Larger string **********", 36);
  32. printf("0x%p test string2: %s\n", y, (char *)y);
  33. free(y);
  34. printf("Allocate 100 nodes 500 bytes each\n");
  35. save = 0;
  36. for (i=0; i<100; i++) {
  37. lp = malloc(500);
  38. if (lp == 0) {
  39. printf("loop 1: malloc returned 0\n");
  40. goto Failed;
  41. }
  42. lp->next = save;
  43. save = lp;
  44. }
  45. printf("freeing 100 nodes\n");
  46. while (save) {
  47. lp = save;
  48. save = save->next;
  49. free(lp);
  50. }
  51. printf("try realloc 100 times \n");
  52. lp = 0;
  53. for (i=1; i<=100; i++) {
  54. lp = realloc(lp, i*200);
  55. if (lp == 0) {
  56. printf("loop 3: realloc returned 0\n");
  57. goto Failed;
  58. }
  59. }
  60. {
  61. void *unused_ret = realloc(lp, 0);
  62. (void) unused_ret;
  63. }
  64. printf("Allocate another 100 nodes 600 bytes each\n");
  65. save = 0;
  66. for (i=0; i<100; i++) {
  67. lp = malloc(600);
  68. if (lp == 0) {
  69. printf("loop 2: malloc returned 0\n");
  70. goto Failed;
  71. }
  72. lp->next = save;
  73. save = lp;
  74. }
  75. printf("freeing 100 nodes\n");
  76. while (save) {
  77. lp = save;
  78. save = save->next;
  79. free(lp);
  80. }
  81. printf("alloc test PASSED\n");
  82. exit(0);
  83. Failed:
  84. printf("!!!!!!!!!!!! alloc test FAILED. !!!!!!!!!!!!!!!\n");
  85. exit(1);
  86. }