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

12 Replies
214 Views

Similar Articles

[PageSpeed] 14


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

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

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

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

Problem with deleting aplication.
Hi, I use iMac G4, 10.3.9. I installed a trial version of "DVD2oneX2". It installs as a bundle. It allows you to use basic functions for 30 days. I was not that happy with it (in my opinion "ffmpegX" does better job) so deleted it (DVD2oneX2 icon from Applications to Trash). A few days later I wanted to check one more function of this software. So downloaded and installed it again. To my surprise after the second installation it was counting "free days" from the date of the first execution/installation. So this time decided to delete it thoroughly: 1. DVD2oneX2 i...

Delete Key Problem
I have only recently gone from using 3.70 (with which I used the PCKeys module 1.00 12 Aug 1995 � Echelon Software 1995 to make the Delete Key (sometimes) delete from the right instead of duplicating the back space) to RISC OS 4.02 with the PC Delete option selected in Configure-->Keyboard. However, I still use a number of simple BASIC and COMAL programs that I originally wrote (or in one case bought) for a BBC B on the RISC PC. These take over the whole machine when run If these programs are run with the PC Delete option selected then there appears to be no way to delete a typing error -...

DELETE problem with MySQL
I've been learning using PHP and MySQL from the tutorial at freewebmasterhelp.com. Everything works fine, except deleting things. The script is invoked with a URL like this: http://www.example.org/test/delete_entry.php?id=35 And here's the script: <? include("dbinfo.inc.php"); $id = $_POST['id']; mysql_connect($server, $user, $password); $query = "DELETE FROM test1 WHERE id = '$id'"; @mysql_select_db($database) or die("Unable to select database."); mysql_query($query); mysql_close(); header("Loca...

delete statement problem
I am using a simple delete statement in my php script (below) $q = "DELETE FROM commenttype WHERE TypeID=".$_POST['selectcat']; the problem is it doesnt delete the whole row it only deletes the text in one of the fields of the row. Has anyone else had a similar problem? It works when I run the sql directly from a program such as mysqlphp ian please ignore Ive sorted it ian "Ian Davies" <iandan.dav@virgin.net> wrote in message news:2SHhg.15450$x53.7020@newsfe1-win.ntli.net... > I am using a simple delete statement in my php script (below) > > $...

problem with deleting files
Hello everybody, I experience a following problem: I try to delete files my code have created using the File.delete() method, and if the delete operation fails, I use File.deleteOnExit(); however, some files still persist to exist. I found an article: http://www.devx.com/Java/Article/22018 (I'm using Windows XP, and I havn't tested my application on other systems). Therefore, my hipothesis is that there are some open streams to these files in my program. The thing is I use someone else's code in my program, and can't really figure out where these open streams are....

operator delete problem.
Hi, Here is my problem: I need to be able to call a virtual method when an object is deleted. class A { public: virtual ~A(); void virtual DestroyRespond(); }; class B : public A { public: virtual ~B(); void virtual DestroyRespond(); }; A::~A() { DestroyRespond(); } void A::DestroyRespond() { printf("destruction of A\n"); } B::~B() { } void B::DestroyRespond() { printf("destruction of B\n"); A::DestroyRespond(); } int main(int argc, char* argv[]) { B *b = new B(); delete b; } obviously this will never work, the virtual method of object B will n...

Problem deleting imrect
Hi all, I have a hard time in deleting the rectangle created using imrect function. Problem is I have two button one to create rectangles (4 or more) & place in the interested position as required. Second Button, (Delete), Choose the required rect to delete and delete. Please help me.. Thanks, Deepu ...