Skip to content
Snippets Groups Projects
Select Git revision
  • cf18a62bd1d0375b436a9f9075811789516011e6
  • main default protected
2 results

README.md

Blame
  • Christian Gram Kalhauge's avatar
    chrg authored
    cf18a62b
    History
    Code owners
    Assign users and groups as approvers for specific file changes. Learn more.

    ShamAlloc

    A dynamic library for making malloc, calloc, and realloc return NULL during tests:

    #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);
      printf("%p\n", a); // Prints "(null)"
    
      // Break malloc, calloc, and realloc after 1 allocations.
      break_alloc(1);
      a = malloc(8);
      b = malloc(8);
      break_alloc(-1);
      printf("%p, %p\n", a, b); // Prints "(null), <pointer>"
    
      return 0;
    }

    or in c++:

    #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";
    }

    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:

    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.

    add_subdirectory(thirdparty/shamalloc)
    
    ... some where later ...
    
    target_link_libraries(my-target
      shamalloc
      )

    Limitations

    Currently, when used with Valgrind or Address Sanitizer, Valgrind and Address Sanitizer will overload the mallocs instead of using the code of this library.

    Valgrind

    To avoid this with Valgrind, use the --soname-synonyms=somalloc flag.

    valgrind --soname-synonyms=somalloc <binary>

    However, this will not overload new operators right now.