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.
Related
I'm trying to mitigate memory leaks.
Obviously the best solution is to not leak memory in the first place.
But in my case, I need to look at existing pointers, and determine if any of them are dynamically allocated and need to be deleted.
Given a specific address/pointer, does C++ provide a way to determine whether the given address points to the heap?
BONUS:
Does C++ provide a way to determine whether a given heap address needs to be deleted with delete[] versus plain delete?
In C++ (and C) a pointer points to any address. To know what type of memory you are pointing to, you need to look at the process memory map. This will be platform specific.
On Linux the /proc/<pid>/maps file contains this info.
However, even if the pointer points to the heap, it still might not be deletable if it is an increment (think arrays) of a newed pointer, or if it was allocated using malloc instead of new.
You should use smart pointers.
You can not know where a pointer points to but using smart pointers means you can avoid having to delete any pointers.
Create your smart pointer at a place in your code that will live as long as you need to use the object it points to. Then, do not pass the smart pointer around your code (unless you need to transfer/share ownership), just pass a reference to the object it points to (or the raw pointer).
When ALL your objects are managed by smart pointers in this way you never have to delete any of the pointers in your code, because you know that there is a smart pointer that will take care of the deletion at the correct time.
void func(Object const& o) { /* ... */ }
void other_func(Object const* pp) { /* ... */ }
// ... somewhere else in the codebase
auto object_ptr = std::make_unique<Object>();
func(*object_ptr); // call function with a reference
other_func(object_ptr.get()); // call function with a raw pointer
BONUS:
No.
It is on you to know what you created, but, again, the smart pointer will take care of that for you:
auto array_ptr = std::make_unique<Object[]>(25); // allocate an array
How can I tell whether a pointer/address is dynamically allocated?
You cannot in general.
The virtual address space of your process is likely to change. So ::operator new (or malloc) is often implemented to use system calls (on Linux, mmap(2) or sbrk(2)) or to reuse previously free-d memory (or ::operator delete-d one).
On Linux, you could parse /proc/self/maps - see proc(5).
Study also the implementation of valgrind, and be aware of the address sanitizer instrumentation options of GCC.
In C++, you could use smart pointers, and the garbage collection handbook explains many related issues (a major one being circular references, which with multi-threading becomes a complex issue).
C++ also has placement new.
On Linux, you can dlopen(3) many plugins, and that also adds complexity, but is quite useful (see Qt or RefPerSys as examples, and read the C++ dlopen minihowto).
I am getting some sort of memory leak with this code. Although is doesnt actually throw any error, when run through Memcheck, it detects a memory leak.
Am I supposed to also delete[] the temporary array or something?
Here is the function it is happening in:
Every memory allocation needs to be paired to exactly one deallocation. When this function ends, the memory pointed to by newBinaryNum has not been deallocated, and the address of that memory is not retained anywhere. Hence, memory leak.
Since you don't use any benefits of dynamic allocation for this BinaryNum object, don't use dynamic allocation. Just declare your variable as BinaryNum newBinaryNum;. Not only will the compiler handle the memory needs of this object, but also your code would be able to benefit from return value optimization.
(Also, you should lean on the standard library a bit more. Your manipulations of binaryAry mimic the functionality of std::vector. Why re-invent the wheel? Your focus in this function should be on the BinaryNum class, so delegate the memory management details to the standard library.)
I got something like this:
ClassA& ClassA::operator>>(char*& string) {
string = (char*)malloc(size);
//read something in that string then return
return *this;
}
Now i want to free the memory allocated in this function without losing the information stored.If i free it before the return i lose information.
I tried to free it inside the constructor but the parameter is not known there or in another function. So how can I do it? I use valgrind to check memory leaks and it pointed me to this malloc.
first, using "malloc" is bad practice, in c++ (you should use new, even if it's for making a char array; use new char[size]);
if you must, add this pointer to a list of pointers this class is responsible for, and in the destructor of this class, go over that list and call delete for each (or free, if you choose to keep using malloc).
another option, is to call delete/free, where this function is being used (not as clean, and may result in memory leaks, as you came across).
as mentioned in another answer here, using string may also solve your problem (although, you'll need to rewrite the code that calls this function).
one other way, may be using a smart pointer. but that may be over complicating things for what you need here (as it means rewriting the code that calls this function).
Writing a dll for file manipulation, I'm running into some issue.
To read bytes from a file via file.read I require a char* array of the desired length.
Since the length is variable, I cannot use
char* ret_chars[next_bytes];
It gives the error that next_bytes is not a constant.
Another topic here in StackOverflow says to use:
char* ret_chars = new char[next_bytes];
Creating it with "new" requires to use "delete" later though, as far as I know.
Now, how am I supposed to delete the array if the return-value of this function is supposed to be exactly this array?
Isn't it a memory leak if I don't use "delete" anywhere?
If that helps anything: This is a DLL I'll be calling from "Game Maker". Therefore I don't have the possibility to delete anything afterwards.
Hope someone can help me!
When you're writing a callback which will be invoked by existing code, you have to follow its rules.
Assuming that the authors of "Game Maker" aren't complete idiots, they will free the memory you return. So you have to check the documentation to find out what function they will use to free the memory, and then you have to call the matching allocator.
In these cases, the framework usually will provide an allocation function which is specially designed for you to use to allocate a return buffer.
Another common approach is that you never return a buffer allocated by the callback. Instead, the framework passes a buffer to your callback, and you simply fill it in. Check the documentation for that possibility as well.
Is there no sample code for writing "Game Maker" plugins/extensions?
It looks like the developers are indeed complete idiots, at least when it comes to design of plugin interfaces, but they do provide some guidance.
Note that you have to be careful with memory management. That is why I declared the resulting string global.
This implies that the Game Maker engine makes no attempt to free the returned buffer.
You too can use a global, or indeed any variable with static storage duration such as a function-local static variable. std::vector<char> would be a good choice, because it's easy to resize. This way, every time the function is called, the memory allocated for the previous call will be reused or freed. So your "leak" will be limited to the amount you return at once.
char* somefunc( void )
{
static std::vector<char> ret_buffer;
ret_buffer.resize(next_bytes);
// fill it in, blah blah
return &ret_buffer[0];
}
// std::string and return ret_string.c_str(); is another reasonable option
Your script in Game Maker Language will be responsible for making a copy of that result string before it calls your function again and overwrites it.
The new char[ n ] trick works with a runtime value, and yes - you need to delete[] the array when you're done with it or it leaks.
If you are unable to change how "Game Maker" (whatever that is) works, then the memory will be leaked.
If you can change "Game Maker" to do the right thing, then it must manage the lifetime of the returned array.
That's the real problem here - the DLL code can't know when it's no longer needed, so the calling code needs to delete it when it's done, but the calling code cannot delete it directly - it must call back to the DLL to delete it, since it was the DLL's memory manager that allocated it in the first place.
Since you say the return value must be a char[], you therefore need to export a second function from your DLL that takes the char[], and calls delete[] on it. The calling code can then call that function when it's finished with the array returned previously.
Use vector <char *> (or vector <char> depending on which you really want - the question isn't entirely clear), that way, you don't need to delete anything.
You can not use new inside a function, without calling delete, or your application will be leaking memory (which is a bad thing, because EVENTUALLY, you'll have no memory left). There is no EASY solution for this, that doesn't have some relatively strict restrictions in some way or another.
The first code sample you quoted allocates memory on the stack.
The second code sample you quote allocates memory on the heap. (Two totally different concepts).
If you are returning the array, then the function allocating the memory does not free it. It is up to the caller to delete the memory. If the caller forgets, then yes, it is a memory leak.
First, if you use new char[]; you can't use delete, but you have to use delete [].
But like you said, if you use new [] in this function without using delete [] at the end your program will be leaking.
If you want a kind of garbage collection, you can use the *smart ptr* now in the standard c++ library.
I think a `shared_ptr` would be good to achieve what you want.
> **Shared ptr** : Manages the storage of a pointer, providing a limited garbage-collection facility, possibly sharing that management with other objects.
Here is some documentation about it : http://www.cplusplus.com/reference/memory/shared_ptr/
Ok, I'll jump in as well.
If the Game Maker doesn't explicitly say it will delete this memory, then you should check to see just how big a buffer it wants and pass in a static buffer of that size instead. This avoids all sorts of nastiness relating to cross dll versioning issues with memory management. There has to be some documentation on this in their code or their API and I strongly suggest you find and read it. Game Maker is a pretty large and well known API so Google should work for info if you don't have the docs yourself.
If you're returning a char pointer, which it looks as though you are, then you can simply call delete on that pointer.
Example:
char * getString()
{
char* ret_chars = new char[next_bytes];
strcpy(ret_chars, "Hello world")
return ret_chars
}
void displayChars()
{
char* chars = getString()
cout << chars
delete [] chars
}
Just be sure to deallocate (delete) all allocated (new'd) pointers or else you'll have memory leaks where the memory is allocated and then not collected after runtime and becomes unusable. A quick and dirty way to glance through and see if you've deallocated all allocated space to count your new's and count your deletes, and they should be 1-to-1 unless some appear in condition or looped blocks.
While learning different languages, I've often seen objects allocated on the fly, most often in Java and C#, like this:
functionCall(new className(initializers));
I understand that this is perfectly legal in memory-managed languages, but can this technique be used in C++ without causing a memory leak?
Your code is valid (assuming functionCall() actually guarantees that the pointer gets deleted), but it's fragile and will make alarm bells go off in the heads of most C++ programmers.
There are multiple problems with your code:
First and foremost, who owns the pointer? Who is responsible for freeing it? The calling code can't do it, because you don't store the pointer. That means the called function must do it, but that's not clear to someone looking at that function. Similarly, if I call the code from somewhere else, I certainly don't expect the function to call delete on the pointer I passed to it!
If we make your example slightly more complex, it can leak memory, even if the called function calls delete. Say it looks like this: functionCall(new className(initializers), new className(initializers)); Imagine that the first one is allocated successfully, but the second one throws an exception (maybe it's out of memory, or maybe the class constructor threw an exception). functionCall never gets called then, and can't free the memory.
The simple (but still messy) solution is to allocate memory first, and store the pointer, and then free it in the same scope as it was declared (so the calling function owns the memory):
className* p = new className(initializers);
functionCall(p);
delete p;
But this is still a mess. What if functionCall throws an exception? Then p won't be deleted. Unless we add a try/catch around the whole thing, but sheesh, that's messy.
What if the function gets a bit more complex, and may return after functionCall but before delete? Whoops, memory leak. Impossible to maintain. Bad code.
So one of the nice solutions is to use a smart pointer:
boost::shared_ptr<className> p = boost::shared_ptr<className>(new className(initializers));
functionCall(p);
Now ownership of the memory is dealt with. The shared_ptr owns the memory, and guarantees that it'll get freed. We could use std::auto_ptr instead, of course, but shared_ptr implements the semantics you'd usually expect.
Note that I still allocated the memory on a separate line, because the problem with making multiple allocations on the same line as you make the function call still exists. One of them may still throw, and then you've leaked memory.
Smart pointers are generally the absolute minimum you need to handle memory management.
But often, the nice solution is to write your own RAII class.
className should be allocated on the stack, and in its constructor, make what allocations with new are necessary. And in its destructor, it should free that memory. This way, you're guaranteed that no memory leaks will occur, and you can make the function call as simple as this:
functionCall(className(initializers));
The C++ standard library works like this. std::vector is one example. You'd never allocate a vector with new. You allocate it on the stack, and let it deal with its memory allocations internally.
Yes, as long as you deallocate the memory inside the function. But by no means this is a best practice for C++.
It depends.
This passes "ownership" of the memory to functionCAll(). It will either need to free the object or save the pointer so that it can be freed later. Passing the ownership of raw pointers like this is one of the easiest ways to build memory issues into your code -- either leaks or double deletes.
In C++ we would not create the memory dynamically like that.
Instead you would create a temporary stack object.
You only need to create a heap object via new if you want the lifetime of the object to be greater than the call to the function. In this case you can use new in conjunction with a smart pointer (see other answers for an example).
// No need for new or memory management just do this
functionCall(className(initializers));
// This assumes you can change the functionCall to somthing like this.
functionCall(className const& param)
{
<< Do Stuff >>
}
If you want to pass a non const reference then do it like this:
calssName tmp(initializers);
functionCall(tmp);
functionCall(className& param)
{
<< Do Stuff >>
}
It is safe if the function that you are calling has acceptance-of-ownership semantics. I don't recall a time where I needed this, so I would consider it unusual.
If the function works this way, it should take its argument as a smart pointer object so that the intent is clea; i.e.
void functionCall(std::auto_ptr<className> ptr);
rather than
void functionCall(className* ptr);
This makes the transfer of ownership explicit, and the calling function will dispose of the memory pointed to by ptr when execution of the function falls out of scope.
This will work for objects created on the stack, but not a regular pointer in C++.
An auto pointer maybe able to handle it, but I haven't messed with them enough to know.
In general, no, unless you want to leak memory. In fact, in most cases, this won't work, since the result of
new T();
in C++ is a T*, not a T (in C#, new T() returns a T).
Have a look at Smart Pointers or A garbage collector for C and C++.