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;
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:
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.