Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Align address on page boundary (fails on kfreebsd otherwise).
[simgrid.git] / teshsuite / xbt / mmalloc_test.c
1 #include "xbt/mmalloc.h"
2 #include "xbt.h"
3 #include <stdio.h>
4 #include <assert.h>
5 #include <fcntl.h>
6 #include <sys/stat.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
10
11 XBT_LOG_NEW_DEFAULT_CATEGORY(test,"this test");
12
13 #define BUFFSIZE 204800
14 #define TESTSIZE 100
15 #define size_of_block(i) (((i % 50)+1)* 100)
16
17 int main(int argc, char**argv)
18 {
19   void *heapA;
20   void *pointers[TESTSIZE];
21   xbt_init(&argc,argv);
22
23   XBT_INFO("Allocating a new heap");
24   unsigned long mask = ~((unsigned long)getpagesize() - 1);
25   void *addr = (void*)(((unsigned long)sbrk(0) + BUFFSIZE) & mask);
26   heapA = xbt_mheap_new(-1, addr);
27   if (heapA == NULL) {
28     perror("attach 1 failed");
29     fprintf(stderr, "bye\n");
30     exit(1);
31   }
32
33   XBT_INFO("HeapA allocated");
34
35   int i, size;
36   for (i = 0; i < TESTSIZE; i++) {
37     size = size_of_block(i);
38     pointers[i] = mmalloc(heapA, size);
39     XBT_INFO("%d bytes allocated with offset %tx", size, ((char*)pointers[i])-((char*)heapA));
40   }
41   XBT_INFO("All blocks were correctly allocated. Free every second block");
42   for (i = 0; i < TESTSIZE; i+=2) {
43     mfree(heapA,pointers[i]);
44   }
45   XBT_INFO("Memset every second block to zero (yeah, they are not currently allocated :)");
46   for (i = 0; i < TESTSIZE; i+=2) {
47     size = size_of_block(i);
48     memset(pointers[i],0, size);
49   }
50   XBT_INFO("Re-allocate every second block");
51   for (i = 0; i < TESTSIZE; i+=2) {
52     size = size_of_block(i);
53     pointers[i] = mmalloc(heapA, size);
54   }
55
56   XBT_INFO("free all blocks (each one twice, to check that double free are correctly catched)");
57   for (i = 0; i < TESTSIZE; i++) {
58     xbt_ex_t e;
59     int gotit = 1;
60
61     mfree(heapA, pointers[i]);
62     TRY {
63       mfree(heapA, pointers[i]);
64       gotit = 0;
65     } CATCH(e) {
66       xbt_ex_free(e);
67     }
68     if (!gotit)
69       xbt_die("FAIL: A double-free went undetected (for size:%d)",size_of_block(i));
70   }
71
72   XBT_INFO("free again all blocks (to really check that double free are correctly catched)");
73   for (i = 0; i < TESTSIZE; i++) {
74     xbt_ex_t e;
75     int gotit = 1;
76
77     TRY {
78       mfree(heapA, pointers[i]);
79       gotit = 0;
80     } CATCH(e) {
81       xbt_ex_free(e);
82     }
83     if (!gotit)
84       xbt_die("FAIL: A double-free went undetected (for size:%d)",size_of_block(i));
85   }
86
87
88   XBT_INFO("Damnit, I cannot break mmalloc this time. That's SO disappointing.");
89   return 0;
90 }