I've been trying to figure out the correct approach for a seemingly simple operation - returning a dynamically allocated array of structs from a function call.
typedef struct Person {
char const* name;
int32_t age;
}
Person* findPersons(int& length) {
length = getNumPersons();
Person persons[length];
for(int i = 0; i < length; i++) {
// do some things
}
return persons;
}
calling the method:
Person* persons = findPersons(length);
if I were to call this method I would receive the length and a pointer to the allocated array of structs, however when I access the array I'm getting a core dump (LoadProhibited). I'm assuming this is because the allocated memory is pushed off the stack once the method is done and I can no longer access it.
The standard approach would be to have the caller allocate the array and pass it to the function to be populated, but what happens when I don't know the size ahead of time? Can I malloc() the array and have the caller responsible for releasing the memory?