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 14358 articles. 0 followers. Post

12 Replies
268 Views

Similar Articles

[PageSpeed] 58


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

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

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

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

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

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

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

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

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

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

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

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

Problems Deleting a File
I am trying to delete a excel file after it has been validated for errors and then put into another folder for processing. My problem is, when I click on the submit button, the excel file is being put into the correct folder, but I am getting a permission denied error on my file2 delete statement below. But if I hit the refresh button, the file gets deleted the way I want it to. What do I need to do to stop the permission denied error? Following is the code I am using to delete the files: function deleteStoreTempFiles() { var file2; var file3; file2 = fso.GetFile(storefolder + filename1)...

delete problem #2
Hello. I have structure : typedef struct SBlog { long id_blog; char bl_name[64]; char bl_domain[64]; } SBLOG, *PBLOG; I made table: BLOG pBlog = new SBlog[10] When I try free memory : delete [] pBlog I get error : Debug Assertion Failed !!!. What I do wrong ??? Thanks for your help GG "GG" <Gs@df.pl> wrote in message news:d1646i$666$1@nemesis.news.tpi.pl... > Hello. Hi. > I have structure : > > typedef struct SBlog { > long id_blog; > > char bl_name[64]; > > char bl_domain[64]; > > } SBLOG, *PBLOG; > > I made ta...

Problem deleting memory
Hi, My application has 2-3 processes.One of these processes creates block data files. (created with sys$create,mapped by crmpsc and then UPDSECW)Memory mapped is deallocated every time. Now I stop my application..all processes are stopped. I restart application, now other process opens these files with sys$open and crmpsc call.(at this time no other process is accessing these files)I just check some variable from file and then deallocate memory by sys$delva and sys$dgblsc calls.Memory is not getting properly deleted.Instead of reusing memory ,It is allocating new memory for each file.Do I nee...