problem with delete[]

helo all, I have a problem with delete[]. after debugging of program
it givs mi error whith abort, retry and ignor.

here is code

if(LOWORD(wParam)==IDC_B1)
{
 TCHAR *text=new TCHAR[256];

  // Set some text

 delete[] text;
}
0
giobs111 (5)
11/20/2009 9:21:51 PM
comp.os.programmer.win32 14434 articles. 0 followers. Post Follow

12 Replies
358 Views

Similar Articles

[PageSpeed] 36
That code will work fine as is. It's the // Set some text part that is 
probably killing you, what do you do?

"B.S" <giobs111@gmail.com> wrote in message 
news:46aa2246-568e-4e97-82b5-24e8d0be764f@a21g2000yqc.googlegroups.com...
> helo all, I have a problem with delete[]. after debugging of program
> it givs mi error whith abort, retry and ignor.
>
> here is code
>
> if(LOWORD(wParam)==IDC_B1)
> {
> TCHAR *text=new TCHAR[256];
>
>  // Set some text
>
> delete[] text;
> } 

0
Todd
11/20/2009 9:29:25 PM
if(LOWORD(wParam)==IDC_B1)
{
 TCHAR *text=new TCHAR[256];
 text=(TCHAR *)FillOpenParams(hwnd,OPEN);
 SetDlgItemText(hwnd,IDC_EDIT1,text);

 delete[] text;
}



FillOpenParams is returning plaithment of file. i tryed without delete
[] text and it worked fine but with it it crushes always.
0
B
11/21/2009 11:22:28 AM
> FillOpenParams is returning plaithment of file. i tryed without delete
> [] text and it worked fine but with it it crushes always.
You allocate some memory and set 'text' to the address of this memory.
Immediately after that, you set 'text' to the result of FillOpenParams.
Now you don't know the address of the allocated memory anymore and
therefore can't free it and so this memory is leaked.
This was problem #1 with your code. Problem #2 is, that you can't use
delete[] to free memory that has not been allocated using new[]. So look
how FillOpenParams allocates the memory of which it returns the address
and use the appropriate method to free this memory - if it must be freed
at all.

Timo
-- 
www.TimoSoft-Software.de - Unicode controls for VB6
"Those who sacrifice freedom for safety deserve neither."
"Demokratie ist per Definition unsicher. Ihr Schutz entsteht aus der
Überzeugung, dass die demokratischen Kräfte überwiegen und sich – auf
demokratischem Wege – durchsetzen."
0
Timo
11/21/2009 2:20:50 PM
On Nov 21, 6:22=A0am, "B.S" <giobs...@gmail.com> wrote:
> =A0text=3D(TCHAR *)FillOpenParams(hwnd,OPEN);

You are probably hoping that line copies text into the text array, but
it does not. It copies a pointer into the text pointer. So the
original text pointer is erased, which is why the later delete []
fails.

What is the type that is returned by FillOpenParams and why are you
casting it to TCHAR*?  Nobody can show you how to fix it without that
missing information.


0
ScottMcP
11/21/2009 2:35:48 PM
This is code of  FillOpenParams:


char *FillOpenParams( HWND hwnd, int ind)
{
 OPENFILENAME open_params = {0};
 char filter[128] = {0};
 char file_name[512] = {0};

 strcat(filter,"All File");
 int index = strlen(filter) + 1;

 filter[index++] = '*';
 filter[index++] = '.';
 filter[index++] = '*';

 open_params.lStructSize = sizeof(OPENFILENAME);
 open_params.hwndOwner = hwnd;
 open_params.lpstrFilter = filter;
 open_params.lpstrFile = file_name;
 open_params.nMaxFile = 1024;
 open_params.lpstrInitialDir = NULL;
 open_params.lpstrFileTitle = NULL;
 open_params.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST ;

 if (ind==OPEN)
 {
  if(!GetOpenFileName(&open_params)) {return 0;}
  return open_params.lpstrFile;
 }

 if (ind==SAVE)
 {
  if(!GetSaveFileName(&open_params)) {return 0;}
  return open_params.lpstrFile;
 }

 else {MessageBox(hwnd,"unnown identifier",0,0);}
}
0
B
11/21/2009 6:24:59 PM
B.S schrieb:
> char *FillOpenParams( HWND hwnd, int ind)
You should not cast char* to TCHAR*. For Unicode builds, a TCHAR is
something different than a char and a typecast doesn't convert an ANSI
string into a Unicode string. With this typecast, the compiler won't
warn you about this problem.

>  char file_name[512] = {0};
>  open_params.lpstrFile = file_name;
>   return open_params.lpstrFile;
The memory occupied by 'file_name' is freed when the function is left,
so you are returning the address to a memory block that no longer will
be valid when it is accessed. Access violation I here you coming...

Timo
-- 
www.TimoSoft-Software.de - Unicode controls for VB6
"Those who sacrifice freedom for safety deserve neither."
"Demokratie ist per Definition unsicher. Ihr Schutz entsteht aus der
Überzeugung, dass die demokratischen Kräfte überwiegen und sich – auf
demokratischem Wege – durchsetzen."
0
Timo
11/21/2009 7:28:58 PM
Use an extra parameter and copy the string:

bool FillOpenParams(HWND hwnd, int ind, char *text)
{

......
open_params.nMaxFile = MAX_PATH;

......

if (ind==OPEN)
 {
  if(!GetOpenFileName(&open_params)) {return false;}
  strcpy(text, open_params.lpstrFile); // copy to the buffer of the caller
  return true;
 }

// change other code likewise

.........

}


// caller
if(LOWORD(wParam)==IDC_B1)
{
 char *text=new char[MAX_PATH];

  // Set some text
 if(FillOpenParams(hwnd, ind, text)) DoSomething();
 
 delete[] text;
}
0
Friedel
11/22/2009 7:23:07 AM
Friedel Jantzen schrieb:
> bool FillOpenParams(HWND hwnd, int ind, char *text)
This is prone to buffer overflows. The function doesn't know the size of
'text' and can only guess how many characters this buffer can take. The
buffer size should be passed, too.

>   strcpy(text, open_params.lpstrFile); // copy to the buffer of the caller
This also is prone to buffer overflows. Strcpy copies until it finds a
null character. It doesn't take the buffer size into account. It's
better to use lstrcpyn here or even better: StringCchCopy.

Timo
-- 
www.TimoSoft-Software.de - Unicode controls for VB6
"Those who sacrifice freedom for safety deserve neither."
"Demokratie ist per Definition unsicher. Ihr Schutz entsteht aus der
Überzeugung, dass die demokratischen Kräfte überwiegen und sich – auf
demokratischem Wege – durchsetzen."
0
Timo
11/22/2009 9:55:46 AM
Am Sun, 22 Nov 2009 10:55:46 +0100 schrieb Timo Kunze:

> Friedel Jantzen schrieb:
>> bool FillOpenParams(HWND hwnd, int ind, char *text)
> This is prone to buffer overflows. The function doesn't know the size of
> 'text' and can only guess how many characters this buffer can take. The
> buffer size should be passed, too.
> 
>>   strcpy(text, open_params.lpstrFile); // copy to the buffer of the caller
> This also is prone to buffer overflows. Strcpy copies until it finds a
> null character. It doesn't take the buffer size into account. It's
> better to use lstrcpyn here or even better: StringCchCopy.
> 
> Timo

You're right. StringCchCopy is recommended. And will work, if you input the
correct max length ;-)
If I know that the source string will fit into the dest. buffer, is it
necessary to do extra checking?

If the user can select only a single file, as the OP posted,
and
open_params.nMaxFile = MAX_PATH;
can the resulting string be longer than MAX_PATH?

Regards,
 Friedel
0
Friedel
11/22/2009 7:36:11 PM
Well, such limitations may be lifted as time moves on and then you'll be
glad to have written the code in a defensive way. ;)
You're right in this specific case. But if you don't avoid strcpy in
general, time will come when you make a failure and decide for strcpy
when you really should use lstrcpyn. I prefer to always use at least
lstrcpyn. It may be less performant, but it's also less likely I make a
failure that may result in a buffer overflow.
You really should pass FillOpenParams the buffer size. Or how do you
make sure that you never call this function from another part of your
code, with a buffer smaller than MAX_PATH chars?

Timo
-- 
www.TimoSoft-Software.de - Unicode controls for VB6
"Those who sacrifice freedom for safety deserve neither."
"Demokratie ist per Definition unsicher. Ihr Schutz entsteht aus der
Überzeugung, dass die demokratischen Kräfte überwiegen und sich – auf
demokratischem Wege – durchsetzen."
0
Timo
11/22/2009 8:57:29 PM
Am Sun, 22 Nov 2009 21:57:29 +0100 schrieb Timo Kunze:

> Well, such limitations may be lifted as time moves on and then you'll be
> glad to have written the code in a defensive way. ;)

I agree, that the defensive way is important to write robust software,
and admit using StringCchCopy very often. IMO especially important on user
input or reading from files, when I do not know the length of the strings.

> You're right in this specific case. But if you don't avoid strcpy in
> general, time will come when you make a failure and decide for strcpy
> when you really should use lstrcpyn. I prefer to always use at least
> lstrcpyn. It may be less performant, but it's also less likely I make a
> failure that may result in a buffer overflow.

I used lstrcpyn for a long time, but switched to StringCchCopy some time
ago.

> You really should pass FillOpenParams the buffer size. Or how do you
> make sure that you never call this function from another part of your
> code, with a buffer smaller than MAX_PATH chars?

In this case I am sure; for single selection file open dialogs I always
provide [MAX_PATH] sized buffers. For my purposes I have written some well
tested standard functions and C++ classes for open/save file dialogs.
However in my posting I tried to reuse the code of the OP as much as
possible (it could be improved...).

Regards,
 Friedel
0
Friedel
11/23/2009 7:13:17 AM
Thanks to all for help and cant you tell me where can i find more
about optimising progams
0
B
11/26/2009 12:27:09 PM
Reply:
Similar Artilces:

ORA-00997 8i trigger long raw problem
Hi, Have a table that i need to populate with 1 record of an identical type from another table in an after insert using a trigger. Usually no problem at all except am forced into using and keeping a field which is a LONG RAW type that now generates an ORA-00997 error. It is all text stored in a LONG RAW format. The table the record needs to be inserted INTO looks like ... RFQ_ID VARCHAR2 15 RFQ_LINE NUMBER 0 TYPE CHAR 1 BITS LONG RAW BITS_LENGTH NUMBER 0 The data the table comes FROM looks like this. PART VARCHAR2 30 PART_LINE NUMBER 0 TYPE CHAR 1 BITS LONG RAW BITS_LENG...

HLA asm problem?
When compiling my HLA code I get (100s of these): .... dted3.asm:182: Error: suffix or operands invalid for `push' dted3.asm:199: Error: suffix or operands invalid for `push' dted3.asm:201: Error: suffix or operands invalid for `push' dted3.asm:221: Error: suffix or operands invalid for `pop' .... When I try it on another Linux box it compiles no problem. Problem box: SuSE 10.0 (kernel 2.6.13-15.8), HLA 1.86, GNU assembler 2.16.91.0.2 20050720 (SuSE Linux) No problem box: SuSE 9.2 (kernel 2.6.8-24), HLA 1.86, GNU assembler 2.15.91.0.2 20040727 (SuSE Linux) ---John jchludz...

a problem
hi, any one of the group ,please solve my problem "is there is any method to find given number is even or odd without using if ,else ,for,while,switch,conditional operators,if else ladders...." On 10 Feb 2007 06:15:46 -0800, bharath539@gmail.com wrote: > any one of the group ,please solve my problem > "is there is any method to find given number is even > or odd without using if ,else ,for,while,switch,conditional > operators,if else ladders...." Yes, there is. Problem solved! /gordon -- [ don't email me supp...

123 VER9 DATE PROBLEM
I am attempting to assign a script to a button that will, when first placed in the proper cell. Enter @now- then do a range value- then place in edit mode- then move the cursor to the start and erase the 2 characters that are the day and await the input of the day I want to use- then it closes with the enter button. I have figured all this out except that the {EDIT} command when used returns the date number. I have found that it does not represent the F2 keystroke. What am I missing here. The cell is formatted date-13-Dec-2006. Thanks Dave David Cartier wrote... >I am at...

Registry Problem in Vista
Since I got Vista, Eudora has been unable to register itself in the registry. Every time I start Eudora, I get a pop up that claims Eudora could not register itself and I have to dismiss the pop up before Eudora will process the mail. This also prevents Eudora from being registered as the default mail client. Has anyone solved that annoyance? (This may be a non-issue for me, since I am considering wiping this notebook, and installing XP. The answer may help me make up my mind.) Rick Rick wrote: > Since I got Vista, Eudora has been unable to register itself in the >...

Menu Problems
figure string = {'Item 1','Item 2','Item 3'}; %Menu menu_hdl = uimenu('Label','Options'); for i = 1:3 uimenu(menu_hdl,'Label',char(string(i)),'Callback','disp(char(string(i )))'); end problem- when uimenu is executed in the for loop variable i is assigned as intended to the label in the menu but when the Callback is executed from the menu it grabs the latest value of i and not the one that should have been assigned when the menu was created. Is there any way to get the desired value of i passed to disp(char(stri...

Read and delete one line from file
Hello I have a shell scripting (bash) problem: - File One gets lines added to it every few minutes. - A shell script should copy the first line into File Two and so on until File Two has 100 lines. - Then File Three is created and the same is done there. Any ideas how I could do that? Thanks -- chlori Sorry if I'm wrong but I think you should simply use 'for' and 'test' instructions (man test and you'll find useful information about). On Saturday 19 August 2006 13:38, Velásquez, Constantin <cvelasquez.gnu@gmail.com> wrote in alt.os.linux: > Sorr...

-1 / +1 problem..
Hello all, I am sorry to ask you again for another problem, as I am a new MATLab user. I have a matrix, rAlphaSet with combinations of +1 and -1. I want to make 2 Matrices rAlpha1 and rAlpha2. I took 2 random numbers r1 and r2. Then I wanted to copy the r1th and r2th column of rAlphaSet to rAplha1 and rAlpha2. But the problem is, when I was running the code, rAlpha1 and rAlpha2 were not having the columns from rAlphaSet. Here is the code: rAlphaSet = (npermutek([-1 1], 2^m))'; rAlpha1 = zeros(2^m,N); rAlpha2 = zeros(2^m,N); for i = 1:N r = randi(256,1); rAlpha1(:,i) = rAlphaSet...

I also need help with Duplex on my IP4000 (Different Problem)
It seems that if I print the same document with exact same settings the print quality of black is paler when using Duplex. It seems that it is not using the same black ink as the Non Duplex printing. Anyone know if this is the case, or should I try a reinstall of the software? Thanks Mike FIRST YOU SHOULD USE ONLY CANON OEM PIGMENTED INK AND SELECT PLAIN PAPER. THEN YOU SHOULD USE A HIGH QUALITY PAPER LIKE HAMMERMILL PREMIUM INKJET PAPER THAT YOU CAN GET AT STAPLES OR OFFICE DEPOT. YOU SHOULD NOT EXPERIENCE THAT. BUT IF YOU DO NOT USE CANON OEM INK THEN YOU ...

Problem with PID.vi
I'm using LABVIEW 4.1 with PID Toolkit I use PID VI. I try to use it in an furnace control but doesn't work. For example, with a set point of 50% output stay still to a level of 25% with the PV following this value. What could be the origin of this problem? Does anyone succeed in working perfectly with PID VI from NI? Advices are welcome Hello hora, My first bit of advice would be to see if you have tuned your PID correctly. It would seem to me that you have proportional gain (K) but no integral (I) to eliminate your SP-PV error. Also watch the "reinitial (F)" input. ...

Problems with compilation for Windows
Trying to prepare FreeWrap for Windows, I've got a problems while compiling Tk 8.5.1 (using free "Express" release of Visual C++, taken from MS-site). The compilation has been interrupted with errors: ============================================================================= link -nologo -machine:IX86 -ltcg -release -opt:ref -opt:icf,3 -subsystem :windows -stack:2300000 -out:".\Release_VC9\wish85s.exe" kernel32.lib user32.lib gdi32.lib "c:\freewrap\tcl8.5.1\win\Release_VC9\tcl85s.lib" .\Release_VC9\tk_St atic\winMain.obj .\Release_VC9\tk_Static\wi...

Problems with wxProcess::OnTerminate()
I'm having problems with the following code. The program (sleep.exe) is executed as expected, but Process::OnTerminate() is never called. (The text "Terminated" is not printed and it never breaks on the function in the debugger). I'm using Visual C++ 7.1 and the program is linked to wxBase with wxUSE_GUI set to 0. All help is apreciated. Here's the code: ------------------------------------ main.cpp --------------------------- #include <wx/process.h> #include <wx/app.h> /********************************************************************...

Problem with comma delimted file
My access table when exported to a comma delimited field gets all messed up because some of the fields have the double quote character - ". Used for measurements and other things. I guess I will have to strip them out. How can I replace the " for a blank space? I am having trouble doing it with the replace command in a sql statement. sqlstatement = "update table set table.[item] = replace(table.[item]," & """""""" & "," + """""" + ")" this gives an error. what to do? On...

Monitor problem
Hi, This shows how long it's been since I've had to do this... I've had to get some material off the RiscStation in front of me at work. It's connected to an IIyama VisionMaster 1451 (nice big monitor), but I'm not getting any display. I've tried pressing 0 on boot (as well as 1 - 4) and T (and R - can't remember what the reset is), but nothing seems to happen. Is there any way I can get a machine to boot so it thinks the monitor is an AKF51 (or whatever the "default" was)? TTFN Paul -- "Logic, my dear Zoe, is merely the ability to be wrong wi...

installation problem uconv-0.4.12. plz help
Hi guys, I need to install Unicode Conversion Module for Ruby version 0.4.12 by Yoshida Masato.I have followed the commands of the link inmy windows system http://www.yoshidam.net/uconv_en.txt but when I use the command "ruby extconf.rb" it create "MakeFile" but when I use "make" command it fails...'make' is not recognized as a command so I can not install Uconv. I use ruby 1.8.5 (2006-12-25 patchlevel 12) [i386-mswin32] How can i solve the problem? Any other way to convert Unicode string to Japanese string. -- Posted via http://www.ruby-forum.com...

problem with auctex
All, I just installed auctex in Windows. And because I uses a portable MikTex (installed in a USB disk), the PATH doesn't include the directory that contains the LaTeX executable commands. Is there a way in Emacs or auctex that can tell auctex where to find the latex commands? For example, can I setup the PATH variables directly in Emacs? Thanks you! caixj "halo" <xuejun.cai@gmail.com> wrote in message news:1160815903.006626.26780@m7g2000cwm.googlegroups.com... > All, > > I just installed auctex in Windows. And because I uses a portable > MikTex (installed...

love problem solution baba ji +917891655189 mumbai #2
love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +917891655189love problem solution baba ji +9178916551...

problems installing...
Cheers all, i realize 6.3 is old, but its the disks we have here. My problem is this. Im trying to install this on old sun O2 machines that already have an existing irix install on them. I basically want to whipe the system clean and start fresh. So i boot up, hit esc, install system software, blablabla select cd rom, reboots, boots up IRIX release 6.3 ..... Current system date is.... Mounting file systems: /dev/dsk/dks0d1s0: Invalid agrument Unable to mount partition: /dev/dskdks0d1s0 on /root. This is your system disk: without it we have nothing on which to install so...

x-> 0 limit problem in MATLAB?
Hi, I recently tried to evaluate the function: f=(x.*exp(x)-exp(x)+1)./x.^2 for values very close to zero. Typically, whenever the argument is zero, I replace it with eps to avoid the singularity in the denominator. It can be shown that the limit of f for x->0 is 0.5. Indeed, for small values of x, f correctly approaches 0.5. E.g: x=1e-6;f=(x.*exp(x)-exp(x)+1)./x.^2 f = 0.5000 However, something strange happens when I make x even smaller: x=1e-7;f=(x.*exp(x)-exp(x)+1)./x.^2 f = 0.5107 And ultimately: x=eps;f=(x.*exp(x)-exp(x)+1)./x.^2 f = ...

ASA to IOS VPN problem
This is a multi-part message in MIME format. --------------080700010601090400070905 Content-Type: text/plain; charset=ISO-8859-15; format=flowed Content-Transfer-Encoding: 7bit Hi all, I am facing a problem trying to establish a tunnel with one of our supplier. Their side is terminated on a IOS router currently unknown type and version (should be 12.2 - 12.4), my side is an ASA 7.2(2), configurations are attached (at least the snippet of the IOS config I was able to get). Apparently Phase 1 completes correctly but P2 fails with "Received non-routine Notify message: No proposal cho...

Xerox Phaser 860
I have been given a Xerox Phaser 860, and now i have started it up, but im getting "Light Stripes" on one of the colors....... i have tried the "Eliminate Light Stripes" test in the printer menu, and i have tried to turn the printer off, and wait a day... I also have tried sending a special PostScript file to the printer to try clean it..... Still im getting 2 Light Stripes in Cyan.... Any ideas.......please Greetings Christian Olesen Denmark On Oct 16, 4:30 pm, "co" <cr...@email.dk> wrote: > I have been given a Xerox Phas...

CPYFRMSTMF problems
We have a file in the IFS with variable length records separated by CRLFs and fields separated by Tabs. We need to transfer this file to a Mainframe. Obviously there are a number of ways to do this, but we are REQUIRED to use a product called XCom (so please don't suggest FTP, MQ, HTTP, ConnectDirect etc. etc.), which can only transfer PFs and SAVFs. My first thought was to use CPYFRMSTF ENDLINFMT *CRLF TABEXPN *NO, but it appears that I cannot do this into a variable length PF - the receiving PF must not be externally described, and CRTPF requires a fixed length file. If I use a fixed le...

Problem with iPhoto/PS interaction.
I can open a RAW file in PS without problems and everything looks fine (Camera Raw 3.7). From iPhoto, I can open and edit a jpeg, but not a raw file. if I try and open a raw file from iPhoto, it switches to PS, but no file opens? This used to work fine, but since switching to Aperture, I haven't used iPhoto for a long time. Anybody have an idea? ...

getopt_long problem
HI! I write a little test program. In witch I use getopt_long function... I included unstd.h , optget.h , stdio.h and stdlib.h when i try to link the program with gcc -o result main.o ( within a makefile , i.e I run make) it says tmp/ccGfK1gp.o(.eh_frame+0x11): undefined reference to `__gxx_personality_v0' collect2: ld returned 1 exit status make: *** [run] Error 1 As result it doesn't generate binary file :( When I remove call of getopt_long functions the problem disapears... Realy strange!... Any ideas ? 10x in advance . -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 jenea ...

passfile problem
I'm attempting to use Pine with the passfile option on SCO Unix to connect to an SMTP server requiring athentication. When I send a message I'm prompted for the password, then asked if I want to save it. I respond "yes" and the password apparently is saved in the correct file. However, when I try to send another message I am again prompted for the password, as if Pine never tries the saved password. What could be going wrong? -- Richard Seeder *** Richard (paapex@att.neteth) wrote in comp.mail.pine today: :) I'm attempting to use Pine with the passfile opti...