I am writing a C API for retrieving data from a hardware device. The data will be returned as a string with approximately 30 bytes of text per item. The problem is there may any number of items. Could just 10 or there could be 10,000. So the returned data could range from 10 x 30 = 300 to 10,000 x 30 = 300,000 bytes.
Initially, the function to get the data was like this:
int get_devicelist(char* devicelist);
So the onus is on the caller to know what they are doing and specify a big enough buffer. Trouble is software using API could be used in many end user applications so the programmer has no end user specific knowledge when they write code to use the API. The only option then is to specify a buffer (or allocate on heap) that is large enough to hold the largest possible amount of data returned.
So for that reason I am thinking about changing the API as here:
char* get_devicelist();
void free_devicelist(char* devlist);
eg in implementation:
char* get_devicelist() {
size_t n = get_devices_size();
char* devlist = malloc(n * 30);
if(devlist)
/* populate devlist */
return devlist;
}
void free_devicelist(char* devlist) {
free(devlist);
}
Or I just inform users to call free on devlist when no longer needed?
I would change the API code to get the number of devices and then allocate an appropriate amount of memory for devicelist. The only downside is that the user is then required to call free_devicelist to free the memory allocated.
Is the second API better? Is there an alternative way?