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?
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:
char String[1024];
strcpy(String, "This is a string");
char *Ptr = strtok(String, " ");
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.
strtok
is a C function that returns a pointer to a perviously allocated memory; strtok
itself doesn't allocate new memory.
If something is allocated with malloc
it has to be freed with free
; anything allocated with new must be free
d with delete
.
Best way to deal with memory allocation/deallocation in modern C++ is to use smart pointers. Take a look at std::shared_ptr
/std::unique_ptr
and don't use raw pointers unless you absolutely have to.
Also using std::string
and std::vector
will remove most of your raw pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With