Is there a problem using malloc and new together?
Hi,
I try to solve a problem in a C++ code I did not write:
When I run the application I get a memory problem, and the message says that memory was allocated with new and ran over with malloc.
Is this really the problem, or is it a simptom for something else?
Is there a known problem with using new and malloc in the same application?
Another note: the problem appears only when compiled with debug information.
The application runs under OS/2 operating system.
The relevant parts of the code:
Code:
void *d_area;
int dsize=10;
d_area = malloc (dsize);
--------
char *penv = getenv ("xxxx");
char *grp;
grp = new char (sizeof (penv) + 1);
Please note that this is only the suspected lines, and the statement int dsize=10; and similar are only shown here for understanding the inportant lines (new and malloc)
Thanks.
Re: Is there a problem using malloc and new together?
Quote:
Originally posted by sapird
Code:
void *d_area;
int dsize=10;
d_area = malloc (dsize);
--------
char *penv = getenv ("xxxx");
char *grp;
grp = new char (sizeof (penv) + 1);
Not that this will fix your problem, but from just a quick glance I noticed that grp is not allocated correctly.....it should be:
Code:
grp = new char[sizeof(penv) + 1];
Re: Is there a problem using malloc and new together?
Quote:
Originally posted by sapird
Hi,
I try to solve a problem in a C++ code I did not write:
When I run the application I get a memory problem, and the message says that memory was allocated with new and ran over with malloc.
Is this really the problem, or is it a simptom for something else?
Is there a known problem with using new and malloc in the same application?
Another note: the problem appears only when compiled with debug information.
The application runs under OS/2 operating system.
Well, you better fix the OS/2 version if you coded this:
Code:
grp = new char (sizeof (penv) + 1);
This is incorrect. What you did here was allocate memory for a single character, and initialized it to sizeof(penv) + 1. The correct syntax is:
Code:
grp = new char [sizeof (penv) + 1];
Be lucky that the OS/2 version hasn't crashed -- yet.
Also, there is no problem with using new and malloc in the same application -- just don't mix up using malloc and delete, new with free. The rules are simple:
Allocate with malloc, deallocate with free.
Allocate with new, deallocate with delete.
Allocate with new[], deallocate with delete[].
My suggestion is to always use new or new[] for C++ programs. There is never a need to use malloc() for a C++ program. The reason why is that new calls the constructor for your object, so if your object was more complex than chars, malloc would just cause more potential problems.
Regards,
Paul McKenzie