Search code examples
arrayscpointersmemorymemory-leaks

Using array as smart point in C


In C++, you can use smart pointer to ensure no memory leak.

But in C, it doesn't support OOP (since smart pointer is based on OOP), does it make sense to use an array to act like a smart pointer, and what do I have to lose if I do this??

To understand what I mean, I want write this code:

int ptr[1] = { 0 };

Instead of:

int *ptr = (int *)malloc(sizeof(int));
*ptr = 0;

Solution

  • For small objects, allocating them with automatic storage has always been the idiomatic way to handle their life-cycle in sync with the scope in which they are defined.

    Allocating objects from the heap allows for:

    • a different life-cycle: if the object needs to remain accessible beyond the end of the current scope
    • an arbitrary size: as stack space is limited, large objects should be allocated from the heap, tested for allocation failure and freed explicitly after use. This is a use case for smart pointers in C++ where the de-allocation is handled transparently. In C the deallocation must be explicit.

    In case multiple objects are allocated in the function, it is recommended to initialize all such pointers to NULL prior to attempting allocation and explicitly free all pointers before returning from the function, both in case of error and success. Null pointers can be safely passed to free() to the code can be clear and simple.