Question

conversion from Char * to CString , mfc, release mode

Asked by: rbhargaw

When I run the following line in Debug mode , I am able to assign value from

ems[i]->coverageType to CoverageType
----------------------------------------------------------------------------------
CoverageType = ems[i]->coverageType;
-----------------------------------------------------------------------------------------
and my VC++ 2005 .NET (unmanaged code) application works fine
But when in release mode the code is breaking in the same line..

 I get an "unhandled exception at access violation reading location".. and the debugger does to the line mentioned in the code section
Why is it so?

CoverageType is (CString) and ems[i]->coverageType is (char*)

ems[i]->coverageType has the value returned from Web Service.

Error shown in the line "PXSTR pszBuffer = GetBuffer( nLength );" present in atlsimpstr.cpp
 
-------------------------------------------------------------------------------------------------------------------
 
void SetString( __in_ecount_opt(nLength) PCXSTR pszSrc, __in int nLength )
	{
		if( nLength == 0 )
		{
			Empty();
		}
		else
		{
			// It is possible that pszSrc points to a location inside of our 
			// buffer.  GetBuffer() might change m_pszData if (1) the buffer 
			// is shared or (2) the buffer is too small to hold the new 
			// string.  We detect this aliasing, and modify pszSrc to point
			// into the newly allocated buffer instead.
			
			if(pszSrc == NULL)
				AtlThrow(E_INVALIDARG);			
				
			UINT nOldLength = GetLength();
			UINT_PTR nOffset = pszSrc-GetString();
			// If 0 <= nOffset <= nOldLength, then pszSrc points into our 
			// buffer
 
			PXSTR pszBuffer = GetBuffer( nLength );
			if( nOffset <= nOldLength )
-----------------------------------------------------

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-26 at 15:20:52ID24684953
Tags

VC++

,

MFC

Topics

Microsoft Programming

,

Windows MFC Programming

,

Microsoft Visual C++.Net

Participating Experts
3
Points
500
Comments
24

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. MFC CString Implementation
    I have read a few magazine articles on how the MFC CString works. I use it frequently and understand it well, but I was wondering if there is a way I can view the actual source code (.cpp file) to see some of the implementation details.
  2. Bug in CString::AllocBuffer()???
    When running an application of mine in debug mode (VC++ 6, I think 5 behaved the same way) I noticed that the output window said "Detected memory leaks". I proceded to try and track down the source of the problem. What I finally found "appears" to be a bu...
  3. _bstr_t  to CString?
    I'm interfacing with an active X thing, and I don't know much about this stuff. The object has a property which seems to be a _bstr_t. I want to get that string and use it in VC++/MFC preferably as a CString. (Actually, all I need to do is grab this string and show it in a...
  4. char to CString
    How can I convert a array of chars to a CString? for example: char* buf[50] CString myString; myString = myString + charTostr(buf);
  5. tokenize a MFC cstring in VC++
    Hi there, Is there anyway I can tokenize a cstring in VC++? For example, if I have this cstring "356,days,12,months,52,weeks" Is there any way I could get back string1 = 356 string2 = days string3 = 12 string4 = months string5 = 52 string6 = weeks ?? thank you.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: itsmeandnobodyelsePosted on 2009-08-26 at 15:37:25ID: 25192973

The GetLength and GetBuffer functions look like CString::GetLength and CString::GetBuffer member functions.

Did you derive from CString? If so, what is PXSTR?

>>>> CoverageType is (CString) and ems[i]->coverageType is (char*)
What has CoverageType to do with the code posted?

>>>> PXSTR pszBuffer = GetBuffer( nLength );
That statement probably fails if nLength < 0 or nLength is a huge integer (greater than that the heap manager can provide as contiguous memory).

 

by: rbhargawPosted on 2009-08-26 at 16:29:00ID: 25193328

Thanks for the reply!

No, I am not deriving from CString , so I don't have any idea of PXSTR too..

Basically the actual code is the below.

CoverageType = ems[i]->coverageType;

I have a requirement where I have to get values from web service response. Now I want to take the response (ems[i]->coverageType) and assign it to a CString varibale and show in an application list box.

So when I run my application in release mode and try to debug, the application is unable to go furthur than this line
CoverageType = ems[i]->coverageType;

So I get an "unhandled exception" dialog error box and when I click on debug to see where the application is failing , it goes  to" PXSTR pszBuffer = GetBuffer( nLength );" present in atlsimpstr.cpp (which is an mfc file)

Let me know if the description is clear.

 

by: itsmeandnobodyelsePosted on 2009-08-26 at 16:47:16ID: 25193414

The GetBuffer is a member function of CString (respectively an internal string class implementing CString) which returns a pointer to a writeable character buffer managed as the internal buffer of a CString. If that statement blows up the nLength probably is negative or a huge number.

Is your app a UNICODE application or MULTIBYTE? Check the properties if you don't know (Release mode configuration).



 

 

by: itsmeandnobodyelsePosted on 2009-08-26 at 16:49:41ID: 25193426

>>>> CoverageType = ems[i]->coverageType;
You could try

  CoverageType = CString(ems[i]->coverageType);


That would cal CString constructor rather than CString::operator= what be give a difference.

 

by: rbhargawPosted on 2009-08-26 at 19:13:58ID: 25194029

My app in MULTIBYTE.. I tried  CoverageType = CString(ems[i]->coverageType) in release mode

but it is giving different error. I have attached the snaphot of the error:

In debug mode the application just hangs on this line
CoverageType = CString(ems[i]->coverageType)

The code which works in DEBUG mode is like this:
-----------------------------------------------------------------
                  CoverageType.GetBuffer(40);
                  CoverageType = ems[i]->coverageType ;
-------------------------------------------------------------------------

I tried like this but that is also not working
CoverageType = CString(ems[i]->coverageType).GetBuffer(40)

 

by: AndyAinscowPosted on 2009-08-26 at 22:38:27ID: 25194882

Just an aside, I think the PXSTR is what microsoft uses internally in the CString.

 

by: pgnatyukPosted on 2009-08-26 at 22:44:17ID: 25194905

Just a guess - is it a multi-threaded application? Do you have a call-back functions that may access this CString variable from different threads?

 

by: AndyAinscowPosted on 2009-08-26 at 22:58:39ID: 25194987

The code which works in DEBUG mode is like this:
-----------------------------------------------------------------
                 CoverageType.GetBuffer(40);
                 CoverageType = ems[i]->coverageType ;
-------------------------------------------------------------------------


Why do you need the call to GetBuffer, you are reassigning the complete string with the next line.

(I suspect you have another problem elsewhere in your code that is causing this in RELEASE mode)

 

by: itsmeandnobodyelsePosted on 2009-08-27 at 00:36:04ID: 25195422

>>>> CoverageType.GetBuffer(40);
That isn't necessary. The allocation made by GetBuffer will be freed with next statement as the operator= of CString would do that before assignment.

It crashes either because ems[i] is out-of-boundary  (check the i) or ems[i] is an invalid pointer e. g. never initialized or already deleted pointer or somehow getting corrupted. The difference between Debug and Release is that the Debugger reserves extra space for debugging purposes, hence any out-of-boundary writing might work in Debug mode and crash in Release mode. Another thing is that in Debug mode all variables were initialized with 0, in Release not. So, any uninitialized pointer may crash in Release and go ok in Debug.

 

by: AndyAinscowPosted on 2009-08-27 at 01:13:22ID: 25195610

From question:
Error shown in the line "PXSTR pszBuffer = GetBuffer( nLength );" present in atlsimpstr.cpp

That is happening in the CoverageType.GetBuffer(40)

 

by: itsmeandnobodyelsePosted on 2009-08-27 at 02:16:32ID: 25195943

>>>> That is happening in the CoverageType.GetBuffer(40)

Don't think so.  The asker told it would crash in

    CoverageType = ems[i]->coverageType ;

Here the internal CSimpleString would call GetBuffer to allocating the space needed for the assignment. I think there is a corruption somehow regarding ems[i]->coverageType. Then, the GetLength on thsi variable would return some negative or huge value what causes the crash. Or the CoverageType is corrupted.

 

by: AndyAinscowPosted on 2009-08-27 at 02:28:31ID: 25196013

Ahhh, I see what you mean.  You think the GetBuffer(40) call succeeds (even though it is redundant).


As you said, probably something like variable 'i' not being initialised is the problem.

 

by: rbhargawPosted on 2009-08-27 at 10:06:47ID: 25200467

I am trying to use following code

char* p = _T(ems[i]->coverageType);
char* p1 = "Amount ";
int i = strlen(p);
int j = strlen(p1);

But here i is coming as some junk value (0x00000b)
j is coming as 0x0000007 which is correct

If I put AfxMessageBox(p) I do see the value as "Amount" but  why I am unable to calculate the strlen of *p?

 

by: AndyAinscowPosted on 2009-08-27 at 10:15:01ID: 25200543

Do you see
"Amount"
or do you see
"Amount           "


Difficult to test with a message box display !

 

by: rbhargawPosted on 2009-08-27 at 10:37:45ID: 25200775

I see like "Amount           "

 

by: AndyAinscowPosted on 2009-08-27 at 10:52:00ID: 25200903

OK, now get back onto topic with your problem.  

 

by: rbhargawPosted on 2009-08-27 at 11:05:24ID: 25201005

So how do I transfer the  values in "ems[i]->coverageType" which will come as "Amount   " or "Text   "

into CSTring variable??

If I use char *p = ems[i]->coverageType , I need to Trim the variable P in later stages.

what solutions do you suggest?

 

by: AndyAinscowPosted on 2009-08-27 at 11:13:59ID: 25201078

>>So how do I transfer...

As you were doing initially (it works in DEBUG mode for you - so it can't be very wrong can it) with the = assignment operator.

I suggest you have a reread at a comment by itsmeandnobodyelse concerning some differences between DEBUG and RELEASE modes.  

 

by: rbhargawPosted on 2009-08-27 at 14:57:43ID: 25203112

I tried as attached in the code snippet and the application worked fine.
 
CoverageType  is not the only variable I am using , there are other variables too which are char* and  I am assign them to CString . All those variable does not fail.
e.g
emsName = ems[i]-> emsName ;
emsName = ems[i]-> emsType;
coverageText = ems[i]->coverageText.



Let me if the solution looks OK.


char * enhCoverage = NULL;
enhCoverage = enhancement[i]->coverageType;
CoverageType = CoverageType.GetBuffer(1024);
CoverageType =enhCoverage;
 
delete enhCoverage

                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: AndyAinscowPosted on 2009-08-27 at 23:07:24ID: 25205274

this line 3 is not required:  CoverageType = CoverageType.GetBuffer(1024);
line 6 - probably very dangerous, that is effectively    delete
enhancement[i]->coverageType;

 

by: itsmeandnobodyelsePosted on 2009-08-28 at 12:53:39ID: 25211096

>>>> But here i is coming as some junk value (0x00000b)
>>>> j is coming as 0x0000007 which is correct
None of those are junk. You might switch of the hex display (right-click at the watch window and uncheck hexidecimal display) and would see that 0x000000b is 11 and 0x00000007 is 7 what both seems fairly correct.

>>>> CoverageType = CoverageType.GetBuffer(1024);
As told a few times by me and Andy the GetBuffer is not needed here. It would reserve an internal buffer of 1024 chars which would be freed with the next assignment.

The purpose of GetBuffer is to provide a writeable buffer (char*) with a CString in case you were calling a function which needs such pointer as an argument. That isn't the case here.

>>>> enhCoverage = enhancement[i]->coverageType;
That shouldn't compile. The right-hand is a CString which could be automatically casted to 'const char*'. If you have a left-hand char* and a right-hand 'const char*' the compiler should deny to compile the assignment statement.

>>>> delete enhCoverage

NEVER DELETE POINTERS YOU DON'T HAVE ALLOCATED.

I don't know what you were trying to do. If using string classes you don't must and need play with pointers. It is not only dangerous as Andy told you but simply a sure method to make your app crash.

 

by: rbhargawPosted on 2009-09-01 at 17:33:14ID: 25237366

I did the stupidiest thing. I never initialized the variable, thinking the code is already there !!. once I assign
 CString CoverageType  = _T("") in the constructor, I was able to assign char * to CString,

Thanks everyone for participating.

 

by: itsmeandnobodyelsePosted on 2009-09-01 at 18:23:12ID: 25237548

>>>> I did the stupidiest thing. I never initialized the variable
I am glad that it works now, but the problem is not solved but only 'moved'. A CString variable don't need to be initialized as it has a default constructor which does the job. If you do

   CString CoverageType  = _T("");

you were only using a different constructor (that which takes a right-hand const char* - or const wchar_t* - literal). If taht solves a problem, it only means that the corruption which happened somewhere between CString construction and CString assignment now was not spoiling the internal pointer of CoverageType. But surely it could spoil any other variable - if not now it could be later. I don't want to confuse you but keep it in mind if some strange things happen later.

 

by: AndyAinscowPosted on 2009-09-01 at 22:32:25ID: 25238214

I agree, a CString actually has a default constructor to provide an initial value of an empty string.  Using the assignment operator has not cured your problem.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...