Question about different string type in VC++

Hi, I want to write a simple Trim() function to trim the spaces around a
LPSTR string.  I created a dialog based app to test the routine, the Trim()
function seems to be OK, but when I close the dialog, it causes General
Protection Fault.  I tried some other approaches but no go.  Since I only
intent to use Ansi string, so I did not use any _T() macro or _TCHAR() macro
in Trim().  Please tell me what I did wrong.  Thanks.

Here are the code fragments:

void CSimpleDlg::OnBTNTest()
{
 // TODO: Add your control notification handler code here
 CString sInput;
 LPSTR sTemp;

 GetDlgItemText(IDC_TXTInput,sInput);                // get the string to be
trimmed

 sTemp=Trim(sInput.GetBuffer(0));

 GetDlgItem(IDC_TXTOutput)->SetWindowText(sTemp);    // display output
}                                                    // after the function
exits, Crash!

LPSTR Trim(LPCSTR s)
{
 LPSTR sResult=new (CHAR);
 int i;

 if(s==NULL) return NULL;

 lstrcpy(sResult,s);

 for(i=0;i<lstrlen(sResult)&&sResult[i]==' ';i++);
 sResult+=i;

 for(i=lstrlen(sResult)-1;i>0&&sResult[i]==' ';i--);
 *(sResult+i+1)='\0';

 return sResult;
}


0
xg1 (25)
10/7/2005 5:05:09 PM
vc.mfc 33608 articles. 0 followers. Follow

3 Replies
539 Views

Similar Articles

[PageSpeed] 46

Hi,

Since you have probably modified the string, you have to call 
ReleaseBuffer(). Your

void CSimpleDlg::OnBTNTest()
{
   // TODO: Add your control notification handler code here
   CString sInput;
   LPSTR sTemp;
 
   GetDlgItemText(IDC_TXTInput,sInput);         // get the string to be 
trimmed

   sTemp=Trim(sInput.GetBuffer(0));
   sInput.ReleaseBuffer();     // must be called since 'sInput' might have 
changed
 
   GetDlgItem(IDC_TXTOutput)->SetWindowText(sTemp);    // display output
}

Hope this helps,
Geo


"xg" wrote:

> Hi, I want to write a simple Trim() function to trim the spaces around a
> LPSTR string.  I created a dialog based app to test the routine, the Trim()
> function seems to be OK, but when I close the dialog, it causes General
> Protection Fault.  I tried some other approaches but no go.  Since I only
> intent to use Ansi string, so I did not use any _T() macro or _TCHAR() macro
> in Trim().  Please tell me what I did wrong.  Thanks.
> 
> Here are the code fragments:
> 
> void CSimpleDlg::OnBTNTest()
> {
>  // TODO: Add your control notification handler code here
>  CString sInput;
>  LPSTR sTemp;
> 
>  GetDlgItemText(IDC_TXTInput,sInput);                // get the string to be
> trimmed
> 
>  sTemp=Trim(sInput.GetBuffer(0));
> 
>  GetDlgItem(IDC_TXTOutput)->SetWindowText(sTemp);    // display output
> }                                                    // after the function
> exits, Crash!
> 
> LPSTR Trim(LPCSTR s)
> {
>  LPSTR sResult=new (CHAR);
>  int i;
> 
>  if(s==NULL) return NULL;
> 
>  lstrcpy(sResult,s);
> 
>  for(i=0;i<lstrlen(sResult)&&sResult[i]==' ';i++);
>  sResult+=i;
> 
>  for(i=lstrlen(sResult)-1;i>0&&sResult[i]==' ';i--);
>  *(sResult+i+1)='\0';
> 
>  return sResult;
> }
> 
> 
> 
0
Geo (129)
10/7/2005 6:34:02 PM
xg,

>  LPSTR sResult=new (CHAR);

This is not a syntax I use but you only appear to be allocating a single
character. So if you copy a string to the same address, you will clearly
overwrite memory that you should not be overwriting.

The simplest solution would be to use a CString, which, by the way, has a
trim method.

-- 
Jonathan Wood
SoftCircuits
http://www.softcircuits.com
Available for consulting: http://www.softcircuits.com/jwood/resume.htm


0
jwood (1291)
10/7/2005 7:30:27 PM
Why are you using GetDlgItemText?  Just create a control variable and do GetWindowText.
You should avoid using API calls that bypass the C++ model.

There is no need to write your own Trim() function; you could just as easily have written
	sInput.TrimLeft();
	sInput.TrimRight();
and be done with it.  Or, if you are using VS.NET, you could just write
	sInput.Trim()
and you are done.

There is no need to use GetBuffer().  Having used GetBuffer(), however, the failure to use
ReleaseBuffer() is significant. But again, you are doing things the hard way; you are
using GetDlgItem to do SetWindowText.  If you had created a control variable, none of this
would even be worth talking about.  See my essay on avoiding GetDlgItem on my MVP Tips
site.

You have allocated a single character buffer, which means you are going to clobber
something serious.  Having allocated a single CHAR to hold the string, you then
incorrectly write an arbitrary amount of data into it, then in addition you fail to delete
it.  

Get rid of ALL this code.  If you want to write Trim(), do it as

void Trim(CString & s)
   {
     s.TrimLeft();
     s.TrimRight();
   }

The simplest form would be to create a control variable and all your code would be
          	CString s;
	c_TextInput.GetWindowText(s);
	s.TrimLeft();
	s.TrimRight();
	c_TextInput.SetWindowText(s);
although, frankly, I would not bother with the SetWindowText.  Just use the trimmed string
internally.

But overall, the code you wrote has so many bugs that the simplest solution is to simply
get rid of all of it.
				joe

On Sat, 8 Oct 2005 01:05:09 +0800, "xg" <xg1@hotmail.com> wrote:

>Hi, I want to write a simple Trim() function to trim the spaces around a
>LPSTR string.  I created a dialog based app to test the routine, the Trim()
>function seems to be OK, but when I close the dialog, it causes General
>Protection Fault.  I tried some other approaches but no go.  Since I only
>intent to use Ansi string, so I did not use any _T() macro or _TCHAR() macro
>in Trim().  Please tell me what I did wrong.  Thanks.
>
>Here are the code fragments:
>
>void CSimpleDlg::OnBTNTest()
>{
> // TODO: Add your control notification handler code here
> CString sInput;
> LPSTR sTemp;
>
> GetDlgItemText(IDC_TXTInput,sInput);                // get the string to be
>trimmed
>
> sTemp=Trim(sInput.GetBuffer(0));
>
> GetDlgItem(IDC_TXTOutput)->SetWindowText(sTemp);    // display output
>}                                                    // after the function
>exits, Crash!
>
>LPSTR Trim(LPCSTR s)
>{
> LPSTR sResult=new (CHAR);
> int i;
>
> if(s==NULL) return NULL;
>
> lstrcpy(sResult,s);
>
> for(i=0;i<lstrlen(sResult)&&sResult[i]==' ';i++);
> sResult+=i;
>
> for(i=lstrlen(sResult)-1;i>0&&sResult[i]==' ';i--);
> *(sResult+i+1)='\0';
>
> return sResult;
>}
>
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15972)
10/8/2005 11:36:52 PM
Reply:

Similar Artilces:

Backup question
I've moved to a new pc and for some reason I thought that when you backed up, a new file was created. Am I right? At the moment, it's just backing up to the backup file. So I've just just my working file and my backup file. Please could you clarify this? Thanks again. In microsoft.public.money, abc wrote: >I've moved to a new pc and for some reason I thought that when you >backed up, a new file was created. Am I right? At the moment, it's >just backing up to the backup file. So I've just just my working file >and my backup file. P...

Question about Xml Schemas "qualified" and "unqualified"
In the textbook, there is a sentence that "Default XML namespaces(xmlns="...") helps a lot, but can also create problems, as a side effect of the rules for automatic qualification. How to understand "automatic qualification" here? Could you please give me an example? Secondly, unless otherwise specified, a schema prescribes that loal elements and attributes must be "unqualified". What does "unqualified" mean? Could you please giv eme an example? Finnaly, could you please tell me what's purpose of using these two things? Thanks a lot! ...

a question and a question
What is the correct name of the type of selection box used in "customizing Word", for example.... you select a word or operation from a list on the left pane and move it over to the right pane. Is there a template to build one of these? thanx You will have to explain more in detail what you are trying to do. -- Stefan Blom Microsoft Word MVP "cliffordjf" <cliffordjf@discussions.microsoft.com> wrote in message news:9856CCA7-8A8E-440C-A0D4-76EE4FA644E2@microsoft.com... > What is the correct name of the type of selection box used in "c...

IF AND question
Hi there, I need a function that can provide one of three answers: 1 2 1 1... 3 3 4 4... ? ? ? ?... If A1 = 1 and A2=3, answer 106; but if A1=1 and A2 = 4, answer 104; but if A1=2, regardless of A2, answer 95. The next function for column B is the same, except the answer is dependent on the value delivered from the column A function. E.g. A3 + 6 or A3 +4 or A3-5 etc. Any help would be most appreciated. -- ***** Many thanks Gamq Use the below formula for your first query. =IF(A1="","",IF(A1=2,95,IF(AND(A1=1,A2=3),106,IF(AND(A1=1,A2=4),104)))) ...

IE8 privacy question
I am running XP-Pro SP3 and considering upgrading from IE7 to IE8. I have read all the feature and benefit articles from MS, but have one question that remains unanswered. In IE8 there is mention of being able to restore previously viewed websites or something to that effect. I think this is on a drop down menu somewhere. 1) Does In-private viewing prevent this? 2) Does manually deleting your complete browsing history clear this? 3) Is there a registry entry that can prevent this action? 4) Is there a group policy change that can prevent this action? In essence for privacy pur...

Question about Paste Special
Hi, I have a problem sometimes with the paste special options when goin from one excel workbook to another. For example, sometimes when I cop data from one workbook and then paste special into another, I get th options that include: All, formulas, values, formats, has the option t transpose the data and paste link among other options. And the sometimes I try and paste data to another workbook and I end up th paste special options: Bitmap Image Object, picture, bitmap, and I als lose the ability to paste link. Well you can do it, but it puts it i as an object. What I want is the first past...

Microsoft Query question
I am trying to use Microsoft Query to get data from my SQL 2000 databases. The problem is that I have a few columns with names that conflict with keywords (like Identity). (Yes. I kow that keywords should be avoided but it is done and cannot be changed.) This is causing a keyword syntax error within the Query application. Oddly enough, even if I do not select the column the error still appears. And when you look at all the columns available, the keyword named column shows up in boldface. When I am doing queries in other programs I put square ("[ ]") brackets around column and table...

Having colour for different values
Hi All, Could someone please help me I have been searching the web for hours trying to solve this puzzle? My formular reads =IF(L19<=22%,"Green","Red") and all I get is the word i have also tried =IF(L20<=22%,N19,N20) and in N19 is a green Yes and in N20 is a red No. What I am looking for is a formular that if a value of less than 22% is entered then that value is red or if over then the value is green. I am at my wits end trying everything to try and solve this. :mad: -- Brento ------------------------------------------------------------------------ Brento'...

Question
Why did the chicken cross the road? -- Dr. Stephen Hopkins, MD "Dr. Stephen Hopkins, MD" <DrStephenHopkinsMD@discussions.microsoft.com> wrote in message news:B8434E21-DDA3-44D7-B39B-CD5A8C33A7BD@microsoft.com... > Why did the chicken cross the road? > -- > Dr. Stephen Hopkins, MD To collect her email, why else? Dr? You should be ashamed to put such a title on an idiotic off topic post !! -- Regards Steve. MS-MVP. MAIL. [DTS] UK. http://www.getsafeonline.org/ mac;1266180 Wrote: > "Dr. Stephen Hopkins, MD" <DrSte...

OWA Question #16
Hello All: Quick Question regarding OWA. We are about to finalize migration from 5.5 to 2003. We have an existing web presence already in DNS a www.mydomain.com. and running on existing web servers. With 5.5 natrually, to access OWA, it was www.mydomain.com/exchange. This will not be possible now since OWA runs off of the Exchange server instead of relying on our web server under 5.5. What's the easiest way to overcome this. Thanks If you can afford the extra license, you'll probably want to run a front-end server so no one is connecting directly to the Exchange database s...

VBA//Oracle Interfacing Question
All, I have been able to correct to my database but I have one question question: Within objSession I want to list all available tables and all available views. How exactly is this done? thank you. Set objSession = CreateObject("OracleInProcServer.XOraSession") Set objDatabase = objSession.OpenDatabase("", "User/Pass", 0) On Nov 16, 12:05=A0pm, jason <jason.mell...@gmail.com> wrote: > All, > > I have been able to correct to my database but I have one question > question: > > Within objSession I want to list all avail...

Text Box Question
Greetings, I have been using Visio for years, however, something has happened and I can't figure out how to undo it. Basically up until today when I added a text box and entered text, the text went horizontal as it was typed. Today when I add a text box and enter text, the text goes vertical. How do I get back to the old behavior? TIA using text container shape adjusting tool (text block tool), make the text container shape wider horizontally. Have you used Asian text font recently?...check help for "vertical text" "Ray Batig" wrote: > Greetings, > &g...

401K questions
I just started a 401K at work and I'm wondering how to deal with it in Money. I've got my paycheck split into different categories currently and now I have to put the 401K amount into a category as well. I didn't see one specifically for this. What do other people use? Should I start using the 401K Manager? I haven't gone through it yet I'm just wondering if it works well and how much benefit I'll get from it. Thanks in advance! Mike You will want to create an investment account for the 401(k) and TRANSFER your contributions from your checking account to the...

If / Then Question
How would I do this: IF A1="N" then I need A2 and A3 to="N/A -- pkniven ----------------------------------------------------------------------- pknivens's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=2767 View this thread: http://www.excelforum.com/showthread.php?threadid=47531 pknivens Wrote: > How would I do this: > > IF A1="N" then I need A2 and A3 to="N/A" Hi pknivens In A2 and A3 use this formula > =IF(A1="N","N/A",""), this will return blank if A1 is not N, if you want it...

Can this VBA for work on text files be modified for a different job ?
I have been using the code below (which, from memory, came from the M-Soft site before I hashed it about) successfully to open 2 text files, appending the whole of one file to the end of the other, then deleting the source file. Now a new task is to; - update all text files in a specified folder by appending a new record. This is to be a daily routine, and there should end up being about 800 to 1000 text files to be updated. - The information for the record that is appended to each file comes from a single text file each day (source file). - The first column of this 'source file' ho...

ROWCOUNT question
Hi All, The below is a UDF that returns the ROWCOUNT for a table. I need to know that value for WHILE loop. How do I take the Returned value from the UDF and load it intio a variable in the SP where it was called from? Or maybe there is another way. ALTER FUNCTION [dbo].[RecCount] ( @TableName CHAR(15) ) RETURNS TABLE AS RETURN ( SELECT Rows FROM sysindexes WHERE id = OBJECT_ID(@TableName) AND indid < 2 ) Thanks, Eric Eric S (xxx_noSpam@Hotmail.com) writes: > The below is a UDF that returns the ROWCOUNT for a table. I need to know > that va...

Exmerge Question #7
When I run Exmerge on a mailbox on my 2003 server to export to a PST, it will delete all emails after the copy. I thought EXmerge would "copy" not delete. is this the default? If so how can I just have it do a copy out to the PST and leave the mailbox alone. thanks Rick in "options", make sure "archive data to target store" is not selected on the "Import procedure" tab... -- Susan Conkey [MVP] "Rick" <drummer10980@gmail.com> wrote in message news:1165509540.777142.38260@16g2000cwy.googlegroups.com... > When I run Exmerge on ...

question about "delete"
I have a pointer: MyWindowClass *p = NULL; p = new MyClass(...); .... delete p; After delete p, does p equal NULL(it is in C++ standard?)? How to decide if p has been deleted? The reason I asked this question is that in my project, there are many code/files use the pointer which I need to determine is it is deleted? Can I use: if(p != NULL) delete p; I guess somewhere p has been deleted, but p still not NULL(possible?), the above code might cause problem. Hi Kathy, I typically just set p to NULL when I delete it: delete p; p = NULL; Then you can check it in other places and ...

More combining companies questions
We too have acquired another company and need to look at all of our options concerning what to do with email. We run Exchange 2003, they run Exchange 2000. What is the best way to combine the two so we can share GAL, free-busy info, etc.? No decisions have been made as far as what we are going to do with their AD. We could of course change their MX record to point to our server, update our RUS, etc., but what if we want to keep an Exchange server at their site? What has to be done to join their server to our Exchange org? If you want sync both GAL,pls check this http://www.microso...

switchboard question 12-26-07
Is there a way to put the names of different switchboard pages on the switchboard form? If you put one name on a switchboard page (in form design view), the same name appears on all the switchboard pages. I understand why this happens, but what if I want the user to be able to know which switchboard s/he is on? Thanks. PS the same thing happens if I go into form design view and put in control tip text. It puts the same text for the same-numbered menu item on two different switchboard pages. "Debbie S." wrote: > Is there a way to put the names of different switchboard ...

Different Invoice Currency
Hi there, Is it possible to have different invoice currency? For example, my base currency is USD. I would like to raise an invoice to a customer in Euro. Payment is done by wire transfer by the customer. When I record the payment of the invoice, the deposit goes into USD account in bank, where I could use the TT rates to record the actual amount deposited in USD. Can anyone let me know if it is possible to raise an invoice in EUR, away from base currency? Thanks in advance Hi, Can MVPs help me with an answer? "Bharathan" wrote: > Hi there, > > Is it possible...

Cannot see what I am typing in the cell in Excel?
Version: 2008 Operating System: Mac OS X 10.6 (Snow Leopard) Processor: Intel Hi Folks, <br><br>I am a newbie convert from PC to Mac and am just getting to grips with Excel for Mac. <br><br>One of the issues I am finding, which I don't know how to 'fix', is that when I am typing something in a cell in Excel I cannot see what I am typing (you can see what you are typing in Excel for Windows, so this is somewhat new to me!). <br><br>I am working around this by having the formula bar turned on, so I can look up at the formula bar and see what I...

Some Questions about Outlook
1. what's the max size of attachment for sending email? 2. newMail notifitor: when there is a new mail, can the tary be changed to other until i check the mail? can it work with hotmail? 3. is there any function likes "To Do List"; calendar require time setting? 4. configure file backup; can i back up all of my setting? -- Me, Who I am On Sun, 7 May 2006 22:17:01 -0700, Dotku <lwjct@hotmail.com> wrote: >1. what's the max size of attachment for sending email? That would depend on your mail server/ISP. >2. newMail notifitor: when there is a new mail, can the ...

Toolbar question
I have created a combo box on my toolbar. I am using 32 x 32 buttons, so my combo box is sitting high up. I would like to move it down to the center of the toolbar. To create it I used the following code, CRect rect; SetButtonInfo(14, IDC_FILTERNAMECB, TBBS_SEPARATOR, 200); GetItemRect(14, &rect); rect.bottom = rect.top + 200; m_cbFilterNames.Create(WS_TABSTOP | WS_VISIBLE | WS_VSCROLL | CBS_DROPDOWNLIST | CBS_HASSTRINGS | CBS_SORT, rect, this, IDC_FILTERNAMECB); How do I tell it to place itself in the center of the toolbar? Here is my code: code is from inherited CToolba...

Simple CRM 3.0 Questions
- If an account is no longer active, what's the process to make it inactive? - Can a lead have multiple contacts, with one acting as the primary contact? - When I create a new lead, what the 'Topic' field usually used for? - When creating a lead, on the Details Page, how can I add entries into the 'Industry' and 'Lead Source' drop down lists? - Will CRM track all e-mails associated with a lead? How do I ensure this? - How do I promote a Lead to an Opportunity to an Account? - What's the real definition of an Opportunity? It seems so grey compared to...