Question

parameter passing and EAX register

Asked by: kansworld

I have a code similiar to the one mentioned below.

the 2nd parameter to mbstowcs() function is const short*. Here getstring() returned cstring objects[ temparary object]  reference has been passed to mbstowcs() which will pass the refence directly from EAX register.

1. Is my understanding true ?
2.  if it is true, what is the scope of this temparary object ? if it is get cleared from EAX register before mbstowcs() uses the object , there is a possiblity of data loss ?
3. is this coding style acceptable ?

thanks in advance.


CString getstring()
{
CString str= _T("test");
return str;
}
 
main()
{
wchar_t * l_wcs;
mbstowcs( l_wcs , getstring(), 4);
}
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

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-09-17 at 23:54:22ID24742405
Topics

Windows MFC Programming

,

Microsoft Visual C++

,

C++ Programming Language

,

Microsoft Programming

,

Assembly Programming Language

Participating Experts
3
Points
500
Comments
25

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. mov array[eax * 4], 0  /* when does multiply happ…
    I know this is not a C question, but maybe some assembly guys look at this section. In the assembly statement: mov dword ptr array[eax * 4], 0 When does the eax register get multiplied by four? Is the resulting index stored anywhere before it is added to "array"...
  2. Getting eax,edx into char[4]
    I am using Micro-C (http://www.dunfield.com) and need to access the pentium's cpu timestampusing opcode 0x0f31. I can't use the datatype "long" as that is not supported by Micro-C. I need to get the 32bit contents of the two registers eax and edx into two char[4] ar...
  3. (AC'97  A3D  EAX) output to 5.1 receiver
    I finally got a 5.1 system and right now I have a mini-stereo to stereo RCA cord connecting my PC (line out) and the sound system receiver. I don't yet have a EAX sound card, but will the sound properly transfer to the system using the cable? Currently mine's an integrated ...

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: evilrixPosted on 2009-09-18 at 00:05:14ID: 25363394

1. All compilers/platforms will do this differently. The EAX register is often used for intrinsic return values from functions.
2. I don't think we can safely generlise about this either
3. Not sure what you mean,

 

by: pgnatyukPosted on 2009-09-18 at 00:12:06ID: 25363429

Your example should work:
http://msdn.microsoft.com/en-us/library/ms364057(VS.80).aspx

if you don't want to worry about it, make just few changes, for example:
const static LPCWSTR s_szTest = L"Test";
LPCWSTR getstring()
{
return m_szTest;
}

main()
{
//everything works.
}

or make getstring as, for example:
BOOL getstring(LPWSTR szText, DWORD nCapacity)
{
wcsncat(szText, L"Test", nCapacity - 1);
return TRUE;
}

If you know about EAX - check yourself - put a breakpoint before getstring() call, "Go to assembly".

evilrix, I'm posting after you, sorry - but I have typed it. :)

It will be great, if you will continue here - I remember your artcile about it?

 

by: evilrixPosted on 2009-09-18 at 00:17:07ID: 25363450

>> evilrix, I'm posting after you, sorry - but I have typed it.
All good views and info are welcome, there is no need to apologize

>> It will be great, if you will continue here - I remember your artcile about it?
The person we really want is Infinity08 as he does assembly programming... it is not my area of expertise.

 

by: pgnatyukPosted on 2009-09-18 at 00:29:21ID: 25363504

Here is almost nothing about the assembly programming.
You already paid attention that I have to analyze huge amounts of code written by other people. So I saw this style in the code and see that it works. But, anyway, it is not something I want to use in my applications.
I remember problems when it was like:
LPCWSTR getstring()
{
   CString str;
   str = L"hello";
  return (LPCWSTR)str;
}
with CString getstring() it works. The object exists on stack. But, even with the RVO, if we will talk about the performance.... str = L"hello" means memory allocation. Example bool getstring(wchar_t* p, unsigned int n) does not allocate additional memory.

 

by: evilrixPosted on 2009-09-18 at 00:31:46ID: 25363520

>> Here is almost nothing about the assembly programming.
At the moment I am awaiting clarification of point 3 since I'm not sure I know what the asker wants to know and I've already given the best answer I can to 1 and 2.

 

by: pgnatyukPosted on 2009-09-18 at 03:23:26ID: 25364392

I attached a short app demonstrating the question - it works.

 

#ifndef WINVER				// Allow use of features specific to Windows XP or later.
#define WINVER 0x0501		// Change this to the appropriate value to target other versions of Windows.
#endif
 
#define _AFXDLL
 
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS	// some CString constructors will be explicit
 
#include <afx.h>
 
CString getstring()
{
	CString str;
	str = L"bye";
	return str;
}
 
int main()
{
	CString str;
	str = L"Hello";
	wprintf(L"test string %s\r\n", str);
	wprintf(L"getstring %s\r\n", getstring());
 
	char p[16] = { 0 };
	wcstombs(p, getstring(), 16);
 
	str = p;
	wprintf(L"converted unicode>mb->unicode %s\r\n", str);
}

                                              
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:
30:

Select allOpen in new window

 

by: kansworldPosted on 2009-09-22 at 22:28:19ID: 25400218

Hi pgnatyuk , thanks for posting the instructions.

As per my understanding,  the highlighted line in the image file - copies the getstring return value to some unnamed pointer and that will be passed to wcstombs() ..?

sorry if you could explain the flow..that would be of great pgnatyuk.

thanks

 

by: kansworldPosted on 2009-09-22 at 22:41:23ID: 25400282

i guess...my intial question is not clear....

I will just paraphrase it ....

when a reference of a functions returned value has been passed to another function [ unnamed ?] , then what is scope of that memory ? who will take care of that unnamed memory? is this memory safe?
when will it be cleared and by whom ? what happens in assembly level for this kind of coding ?

 

by: kansworldPosted on 2009-09-22 at 23:20:46ID: 25400428

Hi evilrix ...
thanks for your immediate response...couldnt reply u as was in vacation...

1. I am using visual studio 6.0 , winXP SP2, intel core 2 duo.
3. I have given other coding style in the below snippet. is this better or safer  than the above ? and why ?

CString getstring()
{
CString str= _T("test");
return str;
}
 
main()
{
wchar_t * l_wcs;
CString l_cs;
l_cs = getstring();
mbstowcs( l_wcs ,l_cs, 4);
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: pgnatyukPosted on 2009-09-22 at 23:36:07ID: 25400494

I can say how I understand it. It helps me, but the desciption will be neither full, nor correct.
From my undestanding all these objects are created and destoyed on stack (as a local variable in a scope of a function). So you are asking not about an unnamed memory but about the stack.
More info:

http://stackoverflow.com/questions/1083215/returning-c-stack-variable

http://stupefydeveloper.blogspot.com/2008/10/c-rvo-and-nrvo.html

I think, CString object confuses us. Check the example below.


 

#include <iostream>
using namespace std;
 
class CTest
{
	int x;
public:
	CTest() : x(0)
	{
		cout << "CTest::CTest()" << "x = " << x << endl;
	}
 
	~CTest()
	{
		cout << "CTest::~CTest()" << endl;
	}
 
	int& X() { return x; }
 
	void test()
	{
		cout << " x = " << x << endl;
	}
};
 
CTest get_test()
{
	CTest test;
	test.X() = 1;
	return test;
}
 
void Test(int n, CTest test)
{
	for (int i = 0; i < n; i++)
	{
		test.test();
		test.X() += i;
	}
}
 
int main()
{
	Test(5, get_test());
	return 0;
}
                                              
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:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:

Select allOpen in new window

 

by: evilrixPosted on 2009-09-23 at 00:06:13ID: 25400598

>> is this better or safer  than the above ? and why ?
Both of your examples will crash since l_wcs is just a pointer with no allocated storage.
http://www.cplusplus.com/reference/clibrary/cstdlib/mbstowcs/

And I'm afraid I still don't really understand the point of the question. Like I said before, from the point of view of the compiler you cannot generlise about the kind of assembly code it will produce, this will vary between compilers and will be different using the same compiler with different levels of optimization.

 

by: pgnatyukPosted on 2009-09-23 at 00:18:20ID: 25400645

Do you mean the example from ID:25400494 will crash?
So from where I took the code?

 

by: kansworldPosted on 2009-09-23 at 01:55:54ID: 25401026

evilrix,  i didnt add those memory allocation code....plz never mind....

the difference i wanted to show was between line no's 10,11,12 in 2nd example and line no #10 in my first example..

highlighted those in attached png. especially the way 2nd parameter of the mbstowcs() call has been passed.

 

by: evilrixPosted on 2009-09-23 at 02:00:47ID: 25401053

>> he difference i wanted to show was between line no's 10,11,12 in 2nd example and line no #10 in my first example..
Ignoring the memory allocation issue the first is more efficient since the second takes a copy of your string before passing it to mbstowcs. The temporary CString returned by getstring will live for the life of that 1 line making it safe to pass the return value into mbstowcs directly. If you want it to last longer than 1 line you must bind it to a const reference and then it'll last for the lifetype of the reference.

CString const & l_cs = getstring();
mbstowcs( l_wcs ,l_cs, 4);


Taking a reference doesn't make a copy but the reference MUST be const (although Visual Studio allows it not to be it's not portable since the C++ Standard demands that temporary r-values can only be bound to const references).

 

by: kansworldPosted on 2009-09-23 at 02:04:29ID: 25401068

pgnatyuk ,
-->From my undestanding all these objects are created and destoyed on stack (as a local variable in a scope of a function).

true. But what will happen to the value which is not assigned to some variable in the caller? the called function will put the return value in EAX regsiter and clear its stack [ or caller might clear it] and control come backs to the caller.
thought it is not assigned to another variable, will the caller moves this value from EAX to its stack ?

 

by: evilrixPosted on 2009-09-23 at 02:10:55ID: 25401096

>> But what will happen to the value which is not assigned to some variable in the caller?
Didn't I just explain that? :)

{http:#25401053}

>> will the caller moves this value from EAX to its stack ?
Also, you really need to forget about this as a EAX value. Like I said, there is no guarantee this is how the value will be returned, it is totally up to the compiler. You just need to know how it works at a C/C++ level. If you worry about the assembly level (unless you have a specific need to) you are just over-complicating things needlessly.

 

by: pgnatyukPosted on 2009-09-23 at 02:19:13ID: 25401133

Absolutely!
Also the source code will look better and it will be much easier to debug it. :)

 

by: kansworldPosted on 2009-09-23 at 02:45:03ID: 25401242

thanks evilrix .
>> The temporary CString returned by getstring will live for the life of that 1 line making it safe to pass the return value into mbstowcs directly. If you want it to last longer than 1 line you must bind it to a const reference and then it'll last for the lifetype of the reference

this is what making me worry..! how does this value life is 1line? if we have const reference, then it will be in the stack and will get cleared along with other stack variables. isnt it ?
 but if we didnt take const reference, what happens ? when I say a scope of a variable is local i can understand that the memory will be allocated in stack after  "{" and will be cleared from stack before "}" . but for this  variable of 1 line life, can I say that it will be in stack of the caller after this function call and will be cleared in the next line ? isnt confusing ?
 I tried to understand the behavior in vc compiler ....couldnt. So moved to assembly level and trying to understand it.  How it gets cleaned in next line ..?

 

by: evilrixPosted on 2009-09-23 at 02:51:23ID: 25401281

>> how does this value life is 1line?
Any temporary created will live for the lifetime of the expression that created it.


>> if we have const reference, then it will be in the stack and will get cleared along with other stack variables. isnt it ?
Like I said, "bind it to a const reference and then it'll last for the lifetype of the reference"
So, if the reference goes out of scope so does the temporary that it bound to it

>> but if we didnt take const reference, what happens ?
Then the temporary is destroyed when the expression that created it ends (basically the current line)

>>  can I say that it will be in stack of the caller after this function call and will be cleared in the next line ?
If not bound to a const reference, that is exactly what will happen -- it goes out of scope.

>> isnt confusing ?
Not really, the life time rules of C/C++ are pretty trivial really :)

>>S o moved to assembly level and trying to understand it.
I promise you that will confuse you more... since the compiler will generate different code depending upon optimization. Forget assembly, concentrate on the lifetime rules of C/C++.

>> How it gets cleaned in next line ..?
Dunno... you don't need to -- that's the compilers job... you just need to know that a temporary only lives for the lifetime for the expression that created (simplest to think of it as the current line) it unless it is bound to a const reference.

 

by: kansworldPosted on 2009-09-23 at 05:05:20ID: 25402119

thanks evilrix..

its really detailed and solved most of the puzzles.. :)

>> Dunno... you don't need to -- that's the compilers job... you just need to know that a temporary only lives for the lifetime for the expression that created

I Agree. I just was worrying about the safety of the program. If I give that memory reference of such a short scoped value to other function ...suppose if that function is asynchronus... wont it be an issue ?
As c++ being converted to assembly instructions and then to binary..wont it be worth knowing it ?

 

by: evilrixPosted on 2009-09-23 at 05:08:18ID: 25402145

>> .suppose if that function is asynchronus... wont it be an issue ?
IT depends what you mean. If you mean from a thread safety point of view then maybe, it depends what it's being used for. From a scoping point of view as long as the reference is in scope the temporary bound to it is still valid.

>> As c++ being converted to assembly instructions and then to binary..wont it be worth knowing it ?
Well, it pays to be aware of what might happen.. but as I said before all compilers generate code differently and even the same compiler will depending upon the optimization... so just don't get too hung up on it.

 

by: kansworldPosted on 2009-09-23 at 22:25:11ID: 31630418

c++ is great as it doesnt hide the details as .net does....!
though I agreed,  I couldnt accept evilrix point as I always understand c++ in relation with asm.

 

by: ModEErfPosted on 2009-10-01 at 15:28:38ID: 25473789

Grade changed from B to an A.

ModEErf
Experts Exchange Moderator

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