Store items by value, not by pointer, for more memory safety
Closed this issue · 1 comments
In e.g. the old THINK Class Library and a few other older frameworks, the array data structure actually accepted an item size, and allocated memory for each item. That way, you could do stuff like:
Array *myArray = MallocArray(sizeof(struct Point));
struct Point myPoint = { 10, 10 };
ArrayAddItem(myArray, &myPoint);
myPoint.y = 200;
ArrayAddItem(myArray, &myPoint);
FreeArray(myArray);
This still covered the pointer case as well, as you could just say
Array *myArray = MallocArray(sizeof(struct Window*));
ArrayAddItem(myArray, &wyWindowPtr);
...
So basically the pointer case is just handled by adding them as pointers-to-pointers. As an optimization, many of these libraries had cover methods for pointer arrays that used a compatible data structure but didn't require the pointer-to-pointer in comparison, get
and add
functions.
This would save you from having to do all the special explanations in your README, and make it harder for people to accidentally use the library wrongly. It would make safe use of the code easier, unsafe use harder, which is always a desirable trait of an API.
Wow! thank you so much for the feedback. I will try to do this, definitely.