C smart pointer library

hacker_compDeveloper Franklin Mathieu is working on a new library that implements smart pointers in C. His primary aim is to bring the following constructs to C:

  • unique_ptr, shared_ptr macros, and smart type attribute
  • Destructor support for cleanup
  • Custom variable metadata on allocation

Here’s an example to demonstrate how smart pointers are to be used:

#include <stdio.h>
#include <csptr/smart_ptr.h>

int main(void) {
    smart int *some_int = unique_ptr(int);
    *some_int = 1;

    printf("%p = %d\n", some_int, *some_int);

    // some_int is destroyed here
    return 0;
}

It’s possible to add a destructor or any other function while allocating a variable or an array. For example:

#include <stdio.h>
#include <csptr/smart_ptr.h>
#include <csptr/array.h>

void print_int(void *ptr, void *meta) {
    (void) meta;
    // ptr points to the current element
    // meta points to the array metadata (global to the array), if any.
     printf("%d\n", *(int*) ptr);
}

int main(void) {
    // Destructors for array types are run on every 
    // element of the array before destruction.
    smart int *ints = unique_ptr(int[10], print_int);

    // Smart arrays are length-aware
        for (size_t i = 0; i < array_length(ints); ++i) {
        ints[i] = i;
    }

    // Not initializing the array before getting out of scope
    // is undefined behavior: beware !
    return 0;
}

The library also allows you to use a different memory allocator than the usual malloc() / free(), supports automatic cleanup in case of errors, destructor macro helper etc.

The library is open source. In addition, the author has written an article to explain the techniques used.

Compilation

Run the following commands to compile the library on your system:

$ git clone https://github.com/Snaipe/c-smart-pointers.git
$ cd c-smart-pointers
$ ./autogen.sh && ./configure && make && sudo make install

On GitHub: C smart pointers

Leave a Reply

Your email address will not be published. Required fields are marked *