I was wondering the protocol for dealing with memory leaks with pointers to dynamic memory being returned in C and C++. For example, strtok returns a char*. Presumably, the pointer that is returned must eventually be freed/deleted. I note that the reference page doesn’t even mention this. Is that because this is simply assumed? Also, how do you know whether to delete or free? Does one have to do research to find out what language each function was originally in, and then assume that all C programs use malloc/free and C++ uses new/delete?
I was wondering the protocol for dealing with memory leaks with pointers to dynamic
Share
strtok does NOT return a pointer to a newly allocated memory, but rather a pointer to a memory location, which has been previously allocated.
Let’s assume this:
Ptr will not point to a newly allocated memory location, but rather to the location of String (if my counting doesn’t fail me right now), with the space getting replaced by a ‘\0’. (
From the reference:
This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.
That also means, that if you were to print out ‘String’ again after strtok has done its work, it would only contain ‘This’, since the string is terminated after that.
As a rule of thumb, you are safe to say, that you only need to free/delete memory you’ve explicitly allocated yourself.
That means:
For each ‘new’ put a ‘delete’, and for each ‘malloc’ put a ‘free’ and you’re good.