#### 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 14422 articles. 0 followers.

12 Replies
334 Views

Similar Articles

[PageSpeed] 31
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
> 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

>  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

 0
B
11/26/2009 12:27:09 PM
Similar Artilces:

problems problems problems
(The short(?) summary) I've got an Access MDB file and a DAO connect with it.. Problem 1 of 2 The below gives me a runtime error 91 Object variable or With block variable not set. I've got the db stuff after the form.show (to make sure all the objects on the form are loaded before attempting to utilize/manipulate them) But it doesn't like it when I use the data object in the form load anyway for some reason.. pffft. Private Sub Form_Load() frmTest1Project.Show datGallery.Recordset.MoveLast datGallery.Recordset.MoveFirst Call LockTextBoxes(frmTest...

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, " & _ ...

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...

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; } 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 ...

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 ...

Delete problem
Hi everyone, I have situation where I am trying to quality control check a "list of lists" for certain values that should be deleted from the list if they are found. I have wrote a few lines of code that I believe should work, but rather than simply deleting a part of the list, mathematica seems to delete the entire list. Below is the situation with a small test dataset: masterlist={{{AEST-01-C-10,1,1,1,2,31,1,C,-2.14},{AEST-01-C-10,1,1,1,4,31,1, C,-1.1},{AEST-01-C-10,2,2,1,2,12,2,C,1.79}},{{AEST-07-E-04,2,1,2,1,10,2, C,1.334},{AEST-07-E-04,2,1,3...

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; } 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 ...

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...

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...

Problems problems....
I've got Fujitsu MAN3184MP and Adaptec 29160 scsi card. Sometimes i have this message "A disk read error occured" , sometimes even bios does not recognize it, sometimes it does but the boot sequence does not start it seems that motherboard bios has problems with it ( so it seems to me, i could be wrong about that assumption) . Then i reset and it all works perfectly. I've noticed a speed degradation in Win XP lately. I'm angry :)) I have LVD/SE terminator, and i think 68pin cable ( not sure about that ). Hope i gave you enough info to try and help. Thanx! -- -...

problem with Delete
Why the record is not deleted in this case ? This is a summary of my statements. Can you see something wrong ? // The table is originally ordered by ID. We want to add a new editor (aEditor): Append; //append a new record FieldByName('ID').AsString:= last record; //assign the ID aID:= FieldByName('ID').AsString; //store ID // Check existence of the new editor name IndexName:= 'EDX'; //order by editor name SetKey; FieldByName('EDITOR...

delete on delete !
Hi, If I do another delete on an object which has been deleted earlier, then how is the system expected to behave ? Is it an unpredictable behavior ?? Thanks Sandeep Sandeep Grover wrote: > Hi, > > If I do another delete on an object which has been deleted earlier, then > how is > the system expected to behave ? > > Is it an unpredictable behavior ?? > Yes, unpredictable. Some will choke, some destructors SEGV, it goes on and on. Sandeep Grover wrote: > If I do another delete on an object which has been deleted earlier, then > how is the system expect...

Delete Problem
I am trying to delete files from a partition of my hard disk but once they have been deleted the space on the hard disk is still occupied and i cannot place new files in the now supposedly free space can anyone help? Michael Smith "Michael Smith" <smithms@blueyonder.co.uk> wrote in message news:5aa869f4.0310070955.3ac35262@posting.google.com... > I am trying to delete files from a partition of my hard disk but once > they have been deleted the space on the hard disk is still occupied > and i cannot place new files in the now supposedly free space can > anyone hel...

delete and delete []
I understand that if you allocate an array using new as follows object * b = new object[n]; then you must free the object as follows: delete [] b; however if you are allocating a char buffer as follows: char * b = new char [n]; then isn't it irrelavant if you use delete b or delete [] b ? (Then only thing I can think of is that if you change the object type from char to some other object then you might have some issues...) "SpreadTooThin" <bjobrien62@gmail.com> wrote in message news:1175274703.360909.214000@p77g2000hsh.googlegroups.com... >I understand that i...

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...

Problem with a problem
Hello, take a grammar G with alphabet {0,1} such that (the word problem for) the language L_G={w in (0+1)*|w\in L(G)} is very complex, say in PSPACE or some higher complexity class. Now consider an "easy" problem EASY like: "Is an element of L_G in L_G?". Well, this seems to be fairly easy because the answer is "yes" in any case. Hence the problem should be of small complexity. But if one models such a decision problem one has to construct a language L with alphabet A such that the word problem for L reflects exactly the decision problem which one is interested...

problem with delete
Hello all, I have class of such tye class Manager { public: static Manager* getInstance(); Worker* getWorker(char* name); private: Manager(...); Worker** workers; int numberOfWorkers; static Manager* instance; }; It is sort of singleton implementation. First call to getInstatnce() calls Manager() constructor which creates dynamically the workers array of pointers to Worker objects and asignes to numberOfWorkers size of that array. getWorker() method searches the proper worker by the name in the workers array, if there is no such worker it looks to specific file that m...

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...

http://LongPathTool.com
http://LongPathTool.com - unlock files in-use by other applications + Delete and Copy Path Too Long Files The application solves the problem with inability to copy and delete files and folders with long paths or locked by some application. They could be created by virus/adware/different OS/other software. Normally one can't access such files under Windows and therefore can't delete them either. Please check other Features for more details. Also you can download the latest evaluation version on our download page. Long Path Tool uses a variety of methods to delete the pers...

Re: How many files can you have in a VMS directory without performance problems? performance problems? performance problems? problems? performance problems? performance problems? problems? perfo
First, does anyone know why Info-VAX goes nuts on subjects from time to time? (Or is the trouble elsewhere?) From: JF Mezei <jfmezei.spamnot@teksavvy.com> > DELETE Z*.*;* > DELETE Y*.*;* > ... > DELETE A*.*;* > > (followed by the numbers). This scheme may be a bit obsolete. See: http://h71000.www7.hp.com/doc/731FINAL/4506/4506pro_014.html#index_x_890 I quote: [...] 5.2.3.1.2 Extended Character Set In addition, OpenVMS V7.2 on Alpha systems and ODS-5 disks includes support for the use of file names, and subdirectory and root subdirectory names, tha...

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.length()) > outLength){ inText = inText.substr(0, outLength); } strcpy(outText, inText.c_str()); if(static_cast<int>(strlen(outText)) < outLength){ for(int i = strlen(outText); i < outLength; i++){ outText[i] = ' '; } } outText[outLength] = static_cast<char>(NULL); } int main(){ char *temp; string name = "some long name"; te...

Problem deleting mails
When I have deleted e-mails I get this message: Data error encountered in folder Folder name: Whatever File name: FOLxxxxx.PMM Pegasus Mail has encountered a consistency problem in the folder whose details are shown above. The error encountered was as follows: ** Probable invalid offset in index record. If the error message starts with the characters '**', then it may be possible to recover from the error by reindexing the folder. Right-click the folder in the folder list and choose the 'Reindex folder' command to attempt this operation. Reindexing a ...

Problem with Array#delete
Hello, I'm baffled by the following problem: I have an Account class and an external array that keeps them in a list. I'm trying to delete the account objects one at a time as needed, by: class Account def quit array_name.delete self end end However, this is deleting every account in the list (array_name == []). I've verified that the account objects are unique. Just for an example, this is the equivalent of what's happening: class Account def quit arr arr.delete self end end a1 = Account.new a2 = Account.new arr = [] arr << a1 arr << a2 a1.quit arr ...