473,761 Members | 10,498 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

simple problem with delete []

Hi All,

I have the following:

const int LENGTH = 5;

void limitNameLength (string inText, char *&outText, int outLength){
if(static_cast< int>(inText.len gth()) outLength){
inText = inText.substr(0 , outLength);
}
strcpy(outText, inText.c_str()) ;
if(static_cast< int>(strlen(out Text)) < outLength){
for(int i = strlen(outText) ; i < outLength; i++){
outText[i] = ' ';
}
}
outText[outLength] = static_cast<cha r>(NULL);
}

int main(){
char *temp;
string name = "some long name";

temp = new char[LENGTH];
cout << "before : " << name << "\n";
limitNameLength (name, temp, LENGTH);
cout << "after : " << temp << "\n";

delete [] temp;
return 0;
}

if I comment out the call to limitNameLength the delete [] works ok. If I
don't the delete [] never returns.....
Can anyone tell me why? As far as I can see all I have done is pass the
array to another function to manipulate it a bit then delete it. Why does
delete not work?

Thanks for your help

Michael
May 12 '07 #1
5 1766
Hello:

When I programed this one in MinGW stdio.It worked very well.

And I didn't find any grammer error in yours.

May 12 '07 #2
"michael" <sp**@begone.ne twrote in message
news:46******** **************@ per-qv1-newsreader-01.iinet.net.au ...
: Hi All,
:
: I have the following:
:
: const int LENGTH = 5;
:
: void limitNameLength (string inText, char *&outText, int outLength){
You can have char* outText - no need to make it a reference
since the function does not change the pointer address itself.
: if(static_cast< int>(inText.len gth()) outLength){
: inText = inText.substr(0 , outLength);
: }
: strcpy(outText, inText.c_str()) ;
: if(static_cast< int>(strlen(out Text)) < outLength){
: for(int i = strlen(outText) ; i < outLength; i++){
: outText[i] = ' ';
: }
: }
All of the previous can be simply written as:
void limitNameLength ( string const& inText
, char *outText, int const outLength)
{
strncpy( outText, inText.c_str(), outLength );
//NB: if outLength<inTex t.size(), there will be no final '\0'

: outText[outLength] = static_cast<cha r>(NULL);
why not just: '\0' ?

This effectively relies on outText having a length
of outLength+1 !

: }
:
: int main(){
: char *temp;
: string name = "some long name";
:
: temp = new char[LENGTH];
: cout << "before : " << name << "\n";
: limitNameLength (name, temp, LENGTH);
: cout << "after : " << temp << "\n";
:
: delete [] temp;
: return 0;
: }
:
: if I comment out the call to limitNameLength the delete [] works ok.
If I
: don't the delete [] never returns.....
: Can anyone tell me why? As far as I can see all I have done is pass
the
: array to another function to manipulate it a bit then delete it. Why
does
: delete not work?

When you allocate an array of size LENGTH, the valid indices
are 0 .. LENGTH-1. limitNameLength writes over outText[LENGTH].

The buffer provided to limitNameLength needs to have 1 more character
than the requested maximum length of the string.
If outLength is to be the maximum buffer size, you could change
the last line to:
outText[outLength-1] = '\0';

--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

May 12 '07 #3
i noticed one line in your code:
>>strcpy(outTex t, inText.c_str()) ;
the length of outText is 5, and also the length of inText is 5, overflow. no
room to store '\0' in outText.
so the calling sequence should be as below:
int main() {
temp = new char[LENGTH];
......
limitNameLength (name, temp, LENGTH-1);
......
delete temp;
......
}
"michael" <sp**@begone.ne tдÈëÏûÏ¢ÐÂÎÅ:4 6************** ********@per-qv1-newsreader-01.iinet.net.au ...
Hi All,

I have the following:

const int LENGTH = 5;

void limitNameLength (string inText, char *&outText, int outLength){
if(static_cast< int>(inText.len gth()) outLength){
inText = inText.substr(0 , outLength);
}
strcpy(outText, inText.c_str()) ;
if(static_cast< int>(strlen(out Text)) < outLength){
for(int i = strlen(outText) ; i < outLength; i++){
outText[i] = ' ';
}
}
outText[outLength] = static_cast<cha r>(NULL);
}

int main(){
char *temp;
string name = "some long name";

temp = new char[LENGTH];
cout << "before : " << name << "\n";
limitNameLength (name, temp, LENGTH);
cout << "after : " << temp << "\n";

delete [] temp;
return 0;
}

if I comment out the call to limitNameLength the delete [] works ok. If I
don't the delete [] never returns.....
Can anyone tell me why? As far as I can see all I have done is pass the
array to another function to manipulate it a bit then delete it. Why does
delete not work?

Thanks for your help

Michael

May 12 '07 #4

"Ivan Vecerina" <_I************ *******@ivan.ve cerina.comwrote in message
news:a5******** *************** ****@news.hispe ed.ch...
"michael" <sp**@begone.ne twrote in message
news:46******** **************@ per-qv1-newsreader-01.iinet.net.au ...
: Hi All,
:
: I have the following:
:
: const int LENGTH = 5;
:
: void limitNameLength (string inText, char *&outText, int outLength){
You can have char* outText - no need to make it a reference
since the function does not change the pointer address itself.
: if(static_cast< int>(inText.len gth()) outLength){
: inText = inText.substr(0 , outLength);
: }
: strcpy(outText, inText.c_str()) ;
: if(static_cast< int>(strlen(out Text)) < outLength){
: for(int i = strlen(outText) ; i < outLength; i++){
: outText[i] = ' ';
: }
: }
All of the previous can be simply written as:
ummm... no it can't
you will notice that I am padding the output string with spaces so it is
always the same length. strncpy() will not do this for me.
void limitNameLength ( string const& inText
, char *outText, int const outLength)
{
strncpy( outText, inText.c_str(), outLength );
//NB: if outLength<inTex t.size(), there will be no final '\0'

: outText[outLength] = static_cast<cha r>(NULL);
why not just: '\0' ?

This effectively relies on outText having a length
of outLength+1 !

: }
:
: int main(){
: char *temp;
: string name = "some long name";
:
: temp = new char[LENGTH];
: cout << "before : " << name << "\n";
: limitNameLength (name, temp, LENGTH);
: cout << "after : " << temp << "\n";
:
: delete [] temp;
: return 0;
: }
:
: if I comment out the call to limitNameLength the delete [] works ok.
If I
: don't the delete [] never returns.....
: Can anyone tell me why? As far as I can see all I have done is pass
the
: array to another function to manipulate it a bit then delete it. Why
does
: delete not work?

When you allocate an array of size LENGTH, the valid indices
are 0 .. LENGTH-1. limitNameLength writes over outText[LENGTH].
yeah, thanks for that........cas e of looking but not seeing :-)
The buffer provided to limitNameLength needs to have 1 more character
than the requested maximum length of the string.
If outLength is to be the maximum buffer size, you could change
the last line to:
outText[outLength-1] = '\0';

--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

May 12 '07 #5
Paolo Maldini wrote:
i noticed one line in your code:
>>strcpy(outTex t, inText.c_str()) ;
the length of outText is 5, and also the length of inText is 5, overflow. no
room to store '\0' in outText.
so the calling sequence should be as below:
int main() {
char*
temp = new char[LENGTH];
......
limitNameLength (name, temp, LENGTH-1);
......
delete temp;
delete[] temp;
......
}
Also, please don't top-post. See my signature.

--
Thomas
http://www.netmeister.org/news/learn2quote.html
May 12 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
26029
by: Westcoast Sheri | last post by:
Any way to do a simple delete from array? In other words, what would be the *easiest* (and fastest php runtime) way to delete "banana" from the following array: $my_array = array( "apple", "banana", "grape", "lime"
3
3696
by: Patchwork | last post by:
Hi Everyone, Please take a look at the following (simple and fun) program: //////////////////////////////////////////////////////////////////////////// ///////////// // Monster Munch, example program #include <list>
6
2566
by: Scott Niu | last post by:
Hi, I have this following simple c++ program, it will produce memory leak ( see what I did below ). My observation also showed that: There will be a mem leak when all the 3 conditions are true: 1. CallControlData does not provide a operator= 2. INUserHandle's operator= returns a object instead of a reference 3. Use CC -g main_leak.C instead of CC main_leak.C to compile. You change any of the above condition, there will be NO mem leak.
13
2366
by: LRW | last post by:
Having a problem getting a onSubmit function to work, to where it popsup a confirmation depending on which radiobutton is selected. Here's what I have: function checkdel() { if (document.getElementById"].value=='1') { confirm('Are you sure you want to delete this file?'); } } ......
2
3096
by: Les Juby | last post by:
I've used a simple javascript for some time (no entries required up in the <head> tag) that asks for a confirmation before deleting. ie. <a href="/delete.asp?which=345 %>" onclick="javascript:return confirm('Are you ABSOLUTELY SURE you want to DELETE this record ?')">Delete record</a> On several sites I use short form constructs to generate a more recognizable button, and would like to use a simple script such as
3
1767
by: Bore Biko | last post by:
Dear, I don't have enought money to by a original Visual C++, so I use Visual C++ 6.0 Enterprise edition, this version doesen't have a HELP. Most of my friends programmers praise C++, as a toll for GUI-s.For GUI-s I use ORACLE tolls (when I work with databases), and Prolog++, and Java... But for me sems better use C++ becouse he is so
3
1769
by: simon | last post by:
I get from database something like this: DAY HOUR PRICE --------------------------------------------- MONDAY 10 100 MONDAY 11 120 MONDAY 12 130 MONDAY 13 140 MONDAY 14 150 TUESDAY 11 90
1
1646
by: E.T. Grey | last post by:
I have been busting my nut over this for pretty much most of the day and it is driving me nuts. I posted this to an mySQL ng yesterday and I have not had any response (I'm pulling my hair out here). Its really a very simple stored procedure but I simply can't seem to get it to work. I have a simple table misc_data described as ff: +-------+------------------+------+-----+---------+-------+
4
2353
by: Dmytro Bablinyuk | last post by:
I came across several possible ways of allocating memory for objects, for example: 1. malloc(sizeof(T)*3)/free - raw memory 2. new T/delete - buffer would be initialized to default-constructed T objects. 3. operator new(sizeof(T)*3)/operator delete - raw memory
2
4208
by: dave | last post by:
Hi, I have searched for the answer for this error message without success. I have seen the question many times though:) I create an ASP.NET project (VS 2005, C#), and use a very simple .mdf file (which I can provide if necessary). I use 'Add new Item' and pick 'DataSet'. I believe this creates a TypedDataSet, CORRECT? I take all the defaults as far as Insert, and I pick the advanced tab and ask for Update Statements and Delete...
0
9945
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9900
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9765
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8768
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6599
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5214
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3863
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3442
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.