Newer
Older
> ShamAlloc! ShamAlloc! ShamAlloc!
> eh.. It's only a model.
A dynamic library for making `malloc`, `calloc`, and `realloc` return `NULL`
during tests:
```c
#include <stdio.h>
#include <shamalloc.h>
int
main () {
void *a; void *b;
// Break malloc, calloc, and realloc after 0 allocations.
break_alloc(0);
a = malloc(8);
// Remember to unbreak malloc again, otherwise printf might fail.
break_alloc(-1);
// Break malloc, calloc, and realloc after 1 allocations.
break_alloc(1);
a = malloc(8);
b = malloc(8);
break_alloc(-1);
// Prints "(null), <pointer>"
printf("%p, %p\n", a, b);
return 0;
}
```
or in c++:
```cpp
#include <iostream>
#include <shamalloc.h>
int
main(int argc, char ** argv) {
break_alloc(0);
try {
int * ptr = new int;
} catch (const std::bad_alloc& e) {
std::cout << "Allocation failed: " << e.what() << "\n";
}
break_alloc(-1);
int * ptr = new int;
std::cout << "Allocation succeded: " << ptr << "\n";
}
```
Also see [test/main.c](test/main.c) and [test/main.cpp](test/main.cpp).
*Why, would I ever do such a thing?* Well, most people forget to check if
`malloc` returns `NULL`, or that `new` can throw an exception. By using this
library you can put a ticking time-bomb under your tests, because it better
to fail early than in production.
## Usage
Either, include in compilation:
```sh
clang -o main main.c libshamalloc.so -I<pathto-shamalloc>/include -ldl
```
Or if you use the `CMake` build system, you can add the code
as as subdirectory, in the `CMakeLists.txt` file.
```cmake
add_subdirectory(thirdparty/shamalloc)
... some where later ...
target_link_libraries(my-target
shamalloc
)
```
If you are testing a C++ program and [Valgrind](https://valgrind.org/), please
use the `shamallocpp` target and `libshamallocpp.so` dynamic library (Also see
the [Valgrind Section](#Valgrind)). This is currently experimental.
## Limitations
Currently, when used with [Valgrind](https://valgrind.org/) or
[Address Sanitizer](https://clang.llvm.org/docs/AddressSanitizer.html), Valgrind
and Address Sanitizer will overload the mallocs instead of using the code
of this library.
### Valgrind
Wiht valgrind, use the `--soname-synonyms=somalloc` flag, and compile and dynamic
link using the C++ version of the library if you are testing a C++ application.
```
valgrind --soname-synonyms=somalloc <binary>
```
### Address Sanitizer
There are courently no workaround.. yet.
### Thread Safty
The library is currently not thread-safe, use with causion.