Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a char pointer (memory leak)

Tags:

c++

gcc

I have a function in my hardware code that returns a char* as such:

char* getText();

I would like to know how this is actually working in the system. In my getText function, I allocated a memory space via alloc to a char*. Then, I simply returned it through that function.

NOW, I had another function retreive this by calling char* receive=getText(), and I deleted receive after making use of it. Can I check if this would causes any memory leak?

like image 701
soulslicer0 Avatar asked Jun 19 '26 09:06

soulslicer0


1 Answers

Since I assume you are on a linux system using GCC to compile you could use valgrind to run your program and guarantee to find any leaks present or even possible memory leaks that could happen.

To answer your question more directly in this specific case, if you can guarantee that you free() receive after you are done using it then you will not have a memory leak. However, if you forget to free() receive and then reassign something to receive, that right there is considered a memory leak. You have lost the handle to the resource you were responsible for freeing and it can no longer be freed.

In general, your code is very C-like and not the C++ way of doing things. Returning a std::string would be more C++-like. In regards to dynamic allocation, malloc() and free() are also the "C way" of doing dynamic allocation. new and delete are the C++ way of doing dynamic allocation.

like image 119
Dean Knight Avatar answered Jun 20 '26 23:06

Dean Knight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!