My question is this: do I have to deallocate memory or is this general format okay?
Yes, you do have to deallocate memory if you allocated memory dynamically. Otherwise you risk the memory use of your program to grow uncontrollably and consume all available memory - or at least consume more than is necessary.
Do functions that return pointers require that I delete the value that is returned?
Just because a function returns a pointer, doesn't necessarily mean that it must be deleted. An example:
int* a_function(int* ptr) {
return ptr + 1;
}
int main() {
int arr[2];
int* iptr = a_function(arr);
// must not delete iptr
}
A function can require the caller to delete the returned pointer. It appears that your do_something
example function is such function. This is a very bad design for a function. If the ownership of an allocation is transferred to the caller, then a smart pointer should be used instead.
return local;
delete local;
It is pointless to have statements after returning. They will never be executed.
int *result{ new int };
result = do_something();
Here, you lose the value returned by new-expression. As a consequence, it is no longer possible to delete
that value - the later delete
deletes the new value instead. Such loss of a pointer value and consequent inability to deallocate the memory is called a memory leak.