problem with delete[]

  • Permalink
  • submit to reddit
  • Email
  • Follow


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
Reply giobs111 (5) 11/20/2009 9:21:51 PM

See related articles to this posting

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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply B 11/26/2009 12:27:09 PM
comp.os.programmer.win32 14274 articles. 0 followers. Post

12 Replies
158 Views

Similar Articles

[PageSpeed] 21

  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

deleting a composite, double-delete problem
Hello. i have a composite which i want to delete. this is a composite which represents a boolean expression (see a previous post of mine with more details at http://groups.google.ca/groups?hl=en&lr=&ie=UTF-8&threadm=AXqqc.89218%24PJ1.865449%40wagner.videotron.net&rnum=1&prev=/groups%3Fq%3Dmatan%2Bnassau%26hl%3Den%26lr%3D%26ie%3DUTF-8%26sa%3DG%26scoring%3Dd ) VariableExp *x = new VariableExp("X"); VariableExp *y = new VariableExp("Y"); BooleanExp expression( new OrExp( new AndExp(new Constant(true), x), new AndExp(x, y) ) ); represents th...

#deleted problem when deleting records from sql server through vba
I have a front-end access database that uses a sql server back-end to link the tables. When I run the following code, the subform displays #deleted in place of the deleted record. What am I doing wrong??? s = "DELETE WMS_FID FROM [tmp_PID] WHERE [WMS_FID]=" & Me.txt_WMS_FID domcd.RunSQL (s) '*** PMP 9/22/07 - Copy the records to be deleted from t_PID to t_PID_Deleted table s = "INSERT INTO t_PID_Deleted ( WMS_FID, S_PER_IK, S_SEQ_NB, MRN_PRE, MRN, PID, EU, LAST_NM, FIRST_NM, MIDDLE_NM, SSN, GENDER, MBR_TYPE, " & _ ...

Problem deleting
Hi, I'm running Access 2002 and have a problem deleting records on a continuous form. I thought it might be due to relationships with two other tables but having deleted these relationships, I'm still not able to delete a record. The code I am using is as follows:- yn = MsgBox("Are you sure to delete all this person's details permanently??", vbYesNo, "Save") If yn = vbNo Then MsgBox ("record not deleted") Else DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70 DoCmd.DoMenuItem acFormBar, acEditMenu, 6, , acMenuVer70 End If...

Problem with Delete
Hi. I am a (not heavy) Mathematica user who is running into a problem with the Delete function. On occasion (but not always, frustratingly) when I have a matrix (list of lists) and ask for deletion of one slot, the kernel actually shuts down and I get a message from Microsoft saying there is a problem and generating a report. Has anyone run into this and know how to get around it? Example: a = {{1,2},{3,4}}; Delete[a,{1,1}] This sometimes bombs. In my case, it's after I have multiplied the matrix by another matrix, but not before. Help, G. Effinger ...

problem with Delete[]
Hello, Delete[] is not removing elements of v in the following function, could anyone tell me why? Rn[N_, p_] := Module[{A, v, c, q, i, j}, A = Table[0, {i, 1, N}, {j, 1, N}]; v = Table[i, {i, 2, N}]; c = 1; For[i = 1, i < N, i++, j = Random[Integer, {1, Dimensions[v][[1]]}]; A[[c, v[[j]]]] = 1; A[[v[[j]], c]] = 1; q = Random[]; If[q > p, c = v[[j]]]; Delete[v, j]; ]; A ] thanks in advance, Heath Heath Gerhardt schrieb: > Hello, > > Delete[] is not removing elements of...

Delete problem
I'm trying to delete a file from my account and the following message appears rm: photo3.JPG: A file or directory in the path name does not exist. What is the problem? thanks in advance andreas aefthimiou@hotmail.com (Andrew) wrote in message news:<b848afcc.0308020255.6a57caec@posting.google.com>... > I'm trying to delete a file from my account and the following message appears > > rm: photo3.JPG: A file or directory in the path name does not exist. > > What is the problem? > > thanks in advance > andreas Hi. Most probably a nonprintable charater ...

deletion problems
I have 2 tables, Orders and Order Details, the same as with the database Nortwindtraders shipped with Access. The table order is linked with the table Order Details through the filed OrderID. It is autonumber in the table orders and number in the table Order Details.I have a very good function deleting a chosen order from a list box called ListOrders. This function is the following Public Function CancelOrders() Dim StrSQL As String strSQL = "DELETE * FROM [order details] WHERE orderID = " & frm!ListOrders & ";" DoCmd.RunSQL strSQL strSQL = "DELETE * FROM...

More on Delete Problems
Here's simple code which bombs for me: a={{1.,2.,3.},{4.,5.,6.}} b = {{1,0,1},{0,-2,3}, {0,1,0}} c = a . b Delete[c,{1,1}] Why? G. Effinger Hi, This code works fine for me on Mathematica 5.0. Maybe you are using an older version of Mathematica? What you are describing sounds (to me) like a bug in Mathematica. Later, Daniel Works on my system $Version 5.0 for Mac OS X (November 19, 2003) a={{1.,2.,3.},{4.,5.,6.}}; b={{1,0,1},{0,-2,3},{0,1,0}}; c=a.b; Delete[c,{1,1}] {{-1.,7.},{4.,-4.,19.}} Bob Hanlon > > From: Gov...

Delete Problem
I have the following line of code: if (MyData) { delete MyData; MyData= NULL; } Below is MyData: SomeDataStructure *MyData; Every time this code segment is called I get a fatal error that causes my program to terminate. I use the debugger and upon reaching this line of code MyData is still valid and still has the correct information in it. I have searched the internet and pretty much figured that it was some sort of memory allocation problem... either I'm deleting what's not there, or even I've read deleting from different stacks? Any ideas as to why this delete ca...