I do not have thorough enough knowledge of C++ to say for myself, but based on what user2079303 has written in their answer, it seems that the theoretical answer to this question is that it is impossible. However, in practice there are many ways to approach this issue.
1. Check the documentation
In most cases, if you're developing software that uses a library, it should have documentation that provides this information. If not, you may want to question whether or not the benefits of using this library really outweigh the costs.
2. Check the source code
If you have access to the source code, you should be able to find out how the memory in question is being allocated. This is most likely more difficult than option 1, but it gives you a definite answer, rather than an answer that someone else wrote (which really should be correct, but doesn't have to be).
3. Use valgrind
Valgrind is a debugging utility tool, not a tool for proving correctness (correct me if I'm wrong), but in the absence of direct access to the resources we need to answer this question, it can be very useful. We can experiment with the following program, where we imagine that in our application we may not have access to the body of MysteryFunctionOne
and MysteryFunctionTwo
:
#include <iostream>
int* MysteryFunctionOne() {
return new int();
}
int* MysteryFunctionTwo() {
return (int *) malloc(sizeof(int));
}
int main() {
int* p1 = MysteryFunctionOne();
int* p2 = MysteryFunctionTwo();
std::cout << std::hex << p1 << std::endl << p2 << std::endl;
// For illustrative purposes, suppose we free both pointers incorrectly
free(p1);
delete p2;
return 0;
}
If we compile and run the above program with valgrind program_name
, we receive two important error messages, the first of which is:
Mismatched free() / delete / delete []
at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x400A2E: main (in <path/to/program>)
Address 0x5ab6c80 is 0 bytes inside a block of size 4 alloc'd
at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x4009A3: MysteryFunctionOne() (in <path/to/program>)
by 0x4009C8: main (in <path/to/program>)
This tells us that we have incorrectly used free
in function main
. The lower half of the error message even lets us know that operator new
was used in MysteryFunctionOne()
. Thus we know we need to delete
the pointer returned by MysteryFunctionOne()
, so we change
free(p1);
to
delete p1;
The second error message we receive is analogous, and from it we learn that we need to free(p2)
.
In this case, even without reading the source code or documentation, valgrind was able to guide us towards correct memory management. In general, this may not always be the case, but it is an option to consider in the absence of the source code or salient documentation.