using "new" and "delete" inside class function - c++

I want to be sure that using new and delete to free heap memory is done as needed.
Following function returns a char *. Inside each function I use new for the returned value, and I delete afterwards.
Is it the right way to free heap memory for function return?
const char *myIOT2::_devName()
{
char *ret = new char[MaxTopicLength2];
if (strcmp(addGroupTopic, "") != 0)
{
snprintf(ret, MaxTopicLength2, "%s/%s/%s", prefixTopic, addGroupTopic, deviceTopic);
}
else
{
snprintf(ret, MaxTopicLength2, "%s/%s", prefixTopic, deviceTopic);
}
return ret;
}
const char *myIOT2::_availName()
{
char *ret = new char[MaxTopicLength2];
const char *DEV = _devName();
snprintf(ret, MaxTopicLength2, "%s/Avail", DEV);
delete DEV;
return ret;
}
To point out: the fact the I DEV: const char *DEV = _devName(); in order to use it as a parameter in snprintf(ret, MaxTopicLength2, "%s/Avail", DEV); just to be able to delete it later as delete DEV; - is this correct?

At least as I see things, you really only have two sane choices here. One is for the caller to handle all the memory management. The other is for the callee to handle all the memory management.
But what you're doing right now (callee handles allocation, caller handles de-allocation) is a path to madness and memory leaks.
If the caller is going to manage the memory, this all becomes fairly simple:
const char *myIOT2::_devName(char *ret, size_t maxlen)
{
if (strcmp(addGroupTopic, "") != 0)
{
snprintf(ret, maxlen, "%s/%s/%s", prefixTopic, addGroupTopic, deviceTopic);
}
else
{
snprintf(ret, maxlen, "%s/%s", prefixTopic, deviceTopic);
}
return ret;
}
If the callee is going to handle all the memory management, you'd normally use std::string. Since you're on an Arduino, however, std::string isn't available, and you need to use their own String class instead. Either way, you simply allocate a String object and put your contents into it. It takes care of the actual memory allocation to hold the contents, and will free its contents when the String object is destroyed.
Given the small amount of memory normally available on an Arduino, having the caller allocate the memory is usually going to work out better. But (especially if this is something that doesn't happen very often, so you won't run into heap fragmentation problems) allocating space on the heap can work reasonably well also.
But I'll repeat: trying to mix memory management so the callee allocates and the caller deletes...is the stuff of nightmares. When you read about C++ circa 1993, and hear about lots of problems with memory leaks...this is exactly the sort of thing that led to them.

ret allocated memory:
const char *myIOT2::_devName()
{
char *ret = new char[MaxTopicLength2];
return ret;
}
And below, you'll see that by deleting DEV, you will free the memory, because it's actually ret. But this time, you should remove ret2 somewhere else since it's the return value and there's no way to delete it inside that scope:
const char *myIOT2::_availName()
{
char *ret2 = new char[MaxTopicLength2];
const char *DEV = _devName();
delete[] DEV;
return ret2;
}
Also, note the following:
char* str = new char [30]; // Give str a memory address.
// delete [] str; // Remove the first comment marking in this line to correct.
str = new char [60]; /* Give str another memory address with
the first one gone forever.*/
delete [] str; // This deletes the 60 bytes, not just the first 30.

Related

copy char* to another char** using dynamic allocation

I am still new in this topic but can someone explain me how can I copy one char* to another char** as parameter without getting memory leaks?
void Hardware::copyString(char** dest, const char* source)
{
size_t length = strlen(source);
auto string = new char[length+1];
strncpy(string, source, length);
string[length] = '\0';
*dest = string;
//need to be freed
free(string); //if i free here the data would getting lost
}
and a ctor:
Hardware::Hardware(const char* name, int cost)
{
copyString(&name_, name);
cost_ = cost;
}
main.cpp
Hardware hard("CPU", 250)
Where should I free this without getting memory leaks and have the right output?
Regardless of the issues in your implementation, the simple answer to your question would be to free it at the destructor.
If you don't want to expose the name_ variable, you can free it inside the destructor of the Hardware class.
Hardware::~Hardware()
{
delete[] name_;
}
If you free is inside the function itself, you're deleting the heap allocation, even though you're passing different variables, because they're pointing to the same memory location.
But, as others suggested, the best way to work with strings is to use std::string.

How to return local array in C++?

char *recvmsg(){
char buffer[1024];
return buffer;
}
int main(){
char *reply = recvmsg();
.....
}
I get a warning:
warning C4172: returning address of local variable or temporary
I would suggest std::vector<char>:
std::vector<char> recvmsg()
{
std::vector<char> buffer(1024);
//..
return buffer;
}
int main()
{
std::vector<char> reply = recvmsg();
}
And then if you ever need char* in your code, then you can use &reply[0] anytime you want. For example,
void f(const char* data, size_t size) {}
f(&reply[0], reply.size());
And you're done. That means, if you're using C API, then you can still use std::vector, as you can pass &reply[0] to the C API (as shown above), and reply to C++ API.
The bottomline is : avoid using new as much as possible. If you use new, then you've to manage it yourself, and you've to delete when you don't need it.
You need to dynamically allocate your char array:
char *recvmsg(){
char* buffer = new char[1024];
return buffer;
}
for C++ and
char *recvmsg(){
char* buffer = malloc(1024);
return buffer;
}
for C.
What happens is, without dynamic allocation, your variable will reside on the function's stack and will therefore be destroyed on exit. That's why you get the warning. Allocating it on the heap prevents this, but you will have to be careful and free the memory once done with it via delete[].
The warning message is correct. You're returning the address of a local array which disappears after the function returns.
You can do this using dynamic memory allocation:
char *recvmsg(){
char *buffer = (char*)malloc(1024);
return buffer;
}
The catch is that you need to make sure you free() the pointer later on to avoid a memory leak.
Alternatively, you can pass the buffer into the function.
void recvmsg(char *buffer,int buffer_size){
// write to buffer
}
void main(){
char buffer[1024];
recvmsg(buffer,1024);
}
This avoids the need for a memory allocation. This is actually the preferred way to do it.
The problem is that buffer lives on the stack and goes out of scope the moment you exit recvmsg.
You could allocate buffer on the heap:
char *recvmsg(){
char *buffer = malloc(1024);
return buffer;
}
Note that now the caller is responsibe for disposing of the allocated memory:
void main(){
char *reply = recvmsg();
free(reply);
}
You have a few options...The way you're doing it now is going to cause undefined behavior as the array will go out of scope once hte function returns. So one option is to dynamically allocate the memory..
char * recmsg()
{
char * array = new char[128];
return array;
}
Just remember to clean it up with delete this way (or free if you used malloc). Second, you could use a parameter...
void recmsg(char * message, int size)
{
if (message == 0)
message = new char[size];
}
Again, the same thing goes for clean up here as with the previous. Also note the check for 0 to make sure you don't call new on a pointer that's been allocated already.
Last, you could use a vector..
std::vector<char> recmsg()
{
std::vector<char> temp;
//do stuff with vector here
return temp;
}
char *recvmsg(){
char *buffer = new char;
cout<<"\nENTER NAME : ";
cin>> buffer;
return buffer;
}
int main(){
char *reply = recvmsg();
cout<<reply;
}
Just to complete the picture:
It is not necessary, to allocate memory with malloc. You can also create the buffer on the stack, but you must create it on a stack frame that lives as long as the consumer of the buffer lives. That was the error of the OP -- when the callee was finished, the buffer was deleted and the caller got a invalid pointer.
So what you can do is this:
void recvmsg(char *buffer, size_t size) {
... do what you want ...
}
void main(void) {
char buffer[1024];
recvmsg(buffer, sizeof(buffer));
}
You could dynamically create the buffer, but then the caller needs to know to free it.
I think it's better to pass in a buffer (assuming recvmsg also fills it)
void recvmsg(char *buffer, size_t size){
}
void main(){
char buffer[1024];
recvmsg(buffer, sizeof(buffer));
}
Even if the caller decides dynamic is better, they will know that they need to free it, and the specific way to do that (free(), delete, delete[], or perhaps something special from a custom allocator)
The problem is that you are returning a pointer to a buffer allocated on the stack. Once the function returns, that buffer is no longer valid.
You are allocating the array on the stack inside of your recvmsg function. Returning a pointer to that memory will at some point lead to undefined behavior if it is dereferenced as the memory will be cleaned up when the function exits.
If you want to return a pointer to memory you will need to allocate it dynamically using malloc.
when you are returning the buffer then as it acting as a pointer to the first location of the array so it will return its address.And the place where you are calling the function there you can make a character pointer which will store this returned address value .After which you can move your pointer and can access all the elements of your array.
how about passing by ref
char buf[1024];
PutStuffInBuff(&buf);

Destructor on const char *

In my program, i have line like this:
const char * str = getStr();
Do i need to call destructor on str [] at the end of function to prevent memory leaks?
Question does not contain enough information to tell, it depends what getStr() does. For example:
const char *getStr() {
return "boo";
}
then you must not call delete.
const char *getStr() {
return new char;
}
then you should call delete str; to avoid a memory leak (and must not call delete[]).
const char *getStr() {
return new char[10];
}
then you should call delete[] str; to avoid a memory leak (and must not call delete).
const char *getStr() {
return 0;
}
then it doesn't matter what you do, calling any kind of delete on str has no effect.
Ownership of resources, and how to release any resources owned, are part of the interface to a function, and should be documented at the same time as you document what the return value actually is.
It all depends on what getStr() does. It may even be that you have to call free on the pointer if getStr() created it with malloc. It may be that getStr() is returning a pointer to a static area (not very thread safe, but it happens) or any number of other things.
Part of the contract and documentation for getStr() should be who owns the pointer it returns.
Here are some examples of possible getStr() functions...
In this case getStr() owns the pointer and you don't have to do anything to free it. OTOH, what's being pointed at may change the next time you call getStr() so you should probably make your own copy if you need to keep it around for any length of time:
const char *getStr()
{
static char buf[30] = "Silly counter";
buf[0] = buf[0] + 1;
return buf;
}
In this case, you will eventually need to call free on the pointer returned:
const char *getStr()
{
return strdup("Silly string");
}
In this case, you will need to call plain old delete on the pointer returned:
const char *getStr()
{
return new char;
}
In this case, you will need to call delete [] on the pointer returned:
const char *getStr()
{
return new char[50];
}
There are many other possibilities. As I stated previously, part of the contract for a function (which should appear in its documentation) is who owns the pointer returned and how that data pointed to must be disposed of if doing so is the caller's responsibility.
It depends on how getStr() has been designed. It could return a pointer to a string that is still owned by someone else (and in this case the answer is no) or it may return a pointer to and the caller becomes the owner (and in this case the answer is yes).
You should check the documentation of getStr to know.
If the ownership of the returned area is of the caller then probably in C++ returning an std::string would have been a much better idea.
It's a good idea to do so if it's going out of scope. I'd recommend also setting the pointer to null to ensure it isn't dangling:
delete[] str;
str = null;

When do I need to deallocate memory?

I am using this code inside a class to make a webbrowser control visit a website:
void myClass::visitWeb(const char *url)
{
WCHAR buffer[MAX_LEN];
ZeroMemory(buffer, sizeof(buffer));
MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, url, strlen(url), buffer, sizeof(buffer)-1);
VARIANT vURL;
vURL.vt = VT_BSTR;
vURL.bstrVal = SysAllocString(buffer);
// webbrowser navigate code...
VariantClear(&vURL);
}
I call visitWeb from another void function that gets called on the handlemessage() for the app.
Do I need to do some memory deallocation here?, I see vURL is being deallocated by VariantClear but should I deallocate memory for buffer?
I've been told that in another bool I have in the same app I shouldn't deallocate anything because everything clear out when the bool return true/false, but what happens on this void?
I think you have some fundamental problems with your understanding of memory management. In this case, no, you don't need to explicitly free any memory. You didn't ever call new, so you don't need to call delete. buffer exists only on the stack, and will vanish when this method returns.
If I might, I'd suggest doing this a bit differently -- I'd start by creating a small class:
class bstr {
VARIANT content;
public:
bstr(char const *url) {
WCHAR buffer[MAX_LEN] = {0};
MultiByteToWideChar(CP_ACP,
MB_ERR_INVALID_CHARS,
url,
strlen(url),
buffer,
sizeof(buffer)/sizeof(buffer[0])-1);
content.V_T = VT_BSTR;
content.bstrVal = SysAllocString(buffer);
}
operator VARIANT const &() { return content; }
~bstr() { VariantClear(&content); }
};
Then your code would change to something like:
void myClass::visitWeb(const char *url) {
your_control.Navigate(bstr(url));
}
and all the allocation and freeing gets handled automatically from there.
Even if you don't do use a class like this, note the change to the call to MultiByteToWideChar. The last parameter is supposed to be the number of WCHAR elements in the buffer, not the number of chars. As it is, you've set up a buffer overrun...
I don't see any news, so I wouldn't expect any deletes.
I guess I'd look at the description of SysAllocString() to see if it allocates any memory that you need to get rid of yourself.

Copy constructor demo (crashing...)

Here is the program...
class CopyCon
{
public:
char *name;
CopyCon()
{
name = new char;
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char;
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete name;
name = NULL;
}
}
};
int main()
{
CopyCon objCopyCon1;
objCopyCon1.name = "Hai";
CopyCon objCopyCon2(objCopyCon1);
objCopyCon1.name = "Hello";
cout<<objCopyCon2.name<<endl;
return 0;
}
Once the code execution completes, when the destructor called, it crashes on 'delete' saying...
Debug Error!
Program: ...
HEAP CORRUPTION DETECTED: after Normal block (#124) at 0x00366990.
CRT detected that the application wrote to memory after end of heap buffer.
(Press Retry to debug the application)
Don't we have to clear the heap memory in destructor. What's wrong with this program? Pls someone help!
Copy constructor works perfectly as intended. But still... !?
The problem is you are allocating only one char in the copy constructor.
In main you are assigning a 4-byte string (remember the null), but when you copy the object, you only allocate enough room for 1 byte.
What you probably want to do is change
name = new char;
to
name = new char[tcslen(objCopyCon.name) + 1];
And in the destructor:
delete name;
to
delete [] name;
Also:
You are assigning "Hai" and "Hello" to objCopyCon1.name which is hiding the memory allocated in the constructor. This memory can never be freed!
You write past the allocated variable and that is undefined behavior.
When the folloing lines run
CopyCon objCopyCon1;
objCopyCon1.name = "Hai";
CopyCon objCopyCon2(objCopyCon1);
_tcscpy() copies 4 characters (3 letters and the null terminator) into a buffer that can legally hold only one character. So you write past the buffer end and this leads to heap corruption.
You need to alocate the buffer of the right size:
CopyCon(const CopyCon &objCopyCon)
{
name = new char[_tcslen(objCopyCon.name) +1];
_tcscpy(name,objCopyCon.name);
}
also you need to change the delete in the destructor to delete[] and also change all other new calls to new[] to avoid undefined behavior.
You are allocating one character and trying copy multiple characters into that memory location. First find out the length of the string then allocate length + 1 characters (extra char to accommodate the NULL character) using new char[length+1] syntax. You need to correspondingly change your destructor to delete[] name.
Besides the new char issue that everyone mentioned, the strings "Hai" and "Hello" reside in read-only memory. This means you cannot delete them (but you do so in your destructor) - this does generate crashes. Your code should not assign to name directly, but use a set function such as:
void set_name(const char *new_name)
{
delete [] name; // delete is a no-op on a NULL pointer
name = new char[tcslen(new_name) + 1];
_tcscpy(name,new_name);
}
I'm surprised that assignment does not produce a compiler warning to be honest. You are assigning a const char * to a char *, which can lead to all sorts of problems like the one you're seeing.
The job of the copy ctor should be to create a copy of the object. So the char array pointed to by name in the both the objects should be of the same size and same content, which is not happening in your case. So change
name = new char; // allocates only one char
to
name = new char[strlen(objCopyCon.name) + 1]; // allocate array of char
You need to allocate enough memory to hold the information you are trying to store. "Hai" is 4 bytes or chars (including the null terminator) and you have only allocated one. You also do not copy strings from one memory location to another using "=". You need to strncpy the string across.
Use std::string it will make your life a million times easier :)
Here the code that works perfect!
class CopyCon
{
public:
char *name;
CopyCon()
{
name = NULL;
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char[_tcslen(objCopyCon.name)+1];
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete[] name;
name = NULL;
}
}
void set_name(const char *new_name)
{
//delete [] name; // delete is a no-op on a NULL pointer
if( NULL != name)
{
delete[] name; name = NULL;
}
name = new char[_tcslen(new_name) + 1];
_tcscpy(name,new_name);
}
};
int main()
{
CopyCon objCopyCon1;
objCopyCon1.set_name("Hai");
CopyCon objCopyCon2(objCopyCon1);
objCopyCon1.set_name("Hello");
cout<<objCopyCon1.name<<endl;
cout<<objCopyCon2.name<<endl;
return 0;
}
Thanks to all for their view points. It really helped!