简体   繁体   中英

Return a char pointer (memory leak)

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?

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.

As people suggest you, use std::string instead of C-like strings. std::string manages automatically its own memory, and has a rich and secure interface. String is moveable by default, so by-value-return does not have any performance penalty.

But if you want to return a pointer (In other words, you want to return a "handle" to the string, not the string itself), consider to use smart-pointers instead of raw-pointers. Smart pointers are leak-free, because its memory magnament is based on RAII . The problem with returning a raw-pointer is that the interface of your function not specifies who would deallocate the string. The caller, or a manager/factory that is used by the function?

If you use unique_ptr as return type, you are specifying that the result string will be deleted when the caller stop using its handle. On the other hand, if you use shared_ptr, you specifies that the string is managed by an internal manager/factory used by the function.

The point with smart pointers is that you do not have to worry about string lifetime/memory magnament .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM