This article is the first of a series that’s gonna cover the building of a C99 library I am working on: gulc, acronym for General Utility Library for C. It’s made mainly for fun and learning purposes. The goal is to implement general utility types and functions I think can be handy when programming in C. These include safe memory related functions and features (such as vector and unordered_map) of C++’s standard library. Many others will be added in the future.
Currently the library has only a simple verify system (similar to assert but implemented with the idea of being used in release builds) and safe memory related functions. You can find the code on Github here.
gulc uses CMake as its build system along with CTest as its test system.
It also tries to emulate C++’s namespaces with macros and prefixes. By default everything gulc provides is prefixed with gulc. This can be turned off by defining GULC_NO_PREFIX before including headers from gulc. This resembles C++’s _using namespace in a way.
Since this article isn’t about implementing a new feature, I just want to give you an example usage of gulc, with a very simple program that allocates memory for two values, initializes and swaps them.
#include <gulc/gulc_memory.h>
#include <stdio.h>
int main(void)
{
int* a = (int*) gulc_SafeAlloc(sizeof(int));
int* b = (int*) gulc_SafeAlloc(sizeof(int));
*a = 5;
*b = 3;
printf("Before swap: a: %d, b: %d\\n", *a, *b);
GULC_SWAP(*a, *b);
printf("After swap: a: %d, b: %d\\n", *a, *b);
// You could as well use GULC_SWAP(a, b)
// and swap the pointers rather than the values
gulc_Free(&a);
gulc_Free(&b);
return 0;
}
The biggest things we can see in this very small example are the SafeAlloc function, which tries to allocate memory and verifies it was successful, then the SWAP macro which under the hood just swaps the necessary amount of bytes needed to swap the two passed values. If you want more control over the passed size you can call Swap directly. The last thing we can notice is that Free actually expects the passed parameter to be a pointer to pointer so that it can not only free the pointed memory but also sets the pointer to NULL in order to avoid having dangling pointers.
This is it for this introduction article to the gulc series, with many others coming soon. In the next article, we are going to implement a C++’s vector clone.
Top comments (0)