Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with pointers to dynamic memory being returned in C/C++

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?

like image 298
Cannoliopsida Avatar asked Dec 27 '22 15:12

Cannoliopsida


2 Answers

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.

like image 59
ATaylor Avatar answered Apr 05 '23 22:04

ATaylor


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 freed 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.

like image 24
Barış Uşaklı Avatar answered Apr 06 '23 00:04

Barış Uşaklı