Free Allocated Memory Error (delete)

A

alan

Hi all,

I have a problem on free allocated memory in C++.
Here is my testing program.
I use VS6.0 to compile it successfully.
But there "delete" statement has error in run time.

Can anybody tell me why there is a problem in delete keyword ?

In my concept, when I use "new" keyword, I should use "delete" keyword
to free allocated memory.


void main()
{
string str1="aaa";
string str2="bbb";
string str3="ccc";
string str4="ddd";

int l= str1.length()+ str2.length() + str3.length() + str4.length();
char *mystr = new char[l+1];

sprintf(mystr,"%s,%s,%s,%s", str1.c_str(), str2.c_str(),
str3.c_str(), str4.c_str());

delete [] mystr; //<-----Problem in here!!

}

Thank you very much.
Alan
 
A

Alf P. Steinbach

* (e-mail address removed) (alan) schriebt:
I have a problem on free allocated memory in C++.
Here is my testing program.
I use VS6.0 to compile it successfully.
But there "delete" statement has error in run time.

Can anybody tell me why there is a problem in delete keyword ?

In my concept, when I use "new" keyword, I should use "delete" keyword
to free allocated memory.

Here you need

#include <string>
using namespace std;

for the rest to compile.

void main()

'main' must have return type 'int'. 'void' isn't allowed by the
standard. So at least in theory you have undefined behavior due
to non-conforming code (there must be an int main).

{
string str1="aaa";
string str2="bbb";
string str3="ccc";
string str4="ddd";

int l= str1.length()+ str2.length() + str3.length() + str4.length();

Style: single character names are evil, and 'l' and 'O' are especially evil.

char *mystr = new char[l+1];

sprintf(mystr,"%s,%s,%s,%s", str1.c_str(), str2.c_str(),
str3.c_str(), str4.c_str());

This is one good reason to avoid 'sprintf' and friends: you're storing
three more bytes into 'mystr' than you have allocated for 'mystr'.

Namely, the commas.

What you have is the infamous buffer overrun, so beloved by crackers.


delete [] mystr; //<-----Problem in here!!

Not surprising, that... ;-)


Instead of 'sprintf' consider using string concatenation, that is,
the '+' and/or '+=' operators, or 'std::eek:stringstream', which is safe.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top