Logo AND Algorithmique Numérique Distribuée

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