testmalloc.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. realloc(lp, 0);
  61. printf("Allocate another 100 nodes 600 bytes each\n");
  62. save = 0;
  63. for (i=0; i<100; i++) {
  64. lp = malloc(600);
  65. if (lp == 0) {
  66. printf("loop 2: malloc returned 0\n");
  67. goto Failed;
  68. }
  69. lp->next = save;
  70. save = lp;
  71. }
  72. printf("freeing 100 nodes\n");
  73. while (save) {
  74. lp = save;
  75. save = save->next;
  76. free(lp);
  77. }
  78. printf("alloc test PASSED\n");
  79. exit(0);
  80. Failed:
  81. printf("!!!!!!!!!!!! alloc test FAILED. !!!!!!!!!!!!!!!\n");
  82. exit(1);
  83. }