strange cout output?

R

RB

I am newbee novice programmer, and I ran across some strange outputs
in an app I was creating that I could not understand. So I reproduced the
strangeness in this very small app for posting.
It must have something to do with mixing printf and cout together in the same
function, which it appears one should not do that. I'm sure you will know what
is going on but I have never ran across this before.
I am compiling with MS VS 6.0 (and old version)
Appreciate any comments or input.

===== entire small app code below, outputs to follow ============
#include <windows.h>
#include <stdio.h>
#include <iostream.h>

struct Hold
{
DWORD pHeld;
} *pHold;

void FuncA( );
void FuncB( );

void main( )
{
DWORD FuncA_addr = (DWORD)FuncA;
__asm
{
push [FuncA_addr]
pop [pHold]
}
FuncA( );
FuncB( );
}

void FuncA( )
{
printf("Inside FuncA( )\n");
printf("printf Addr of FuncA( ) is 0x%X\n", pHold);
cout << "cout Addr of FuncA( ) is " << pHold << "\n";
}

void FuncB( )
{
printf("Inside FuncB( )\n");
}

===== end code, begin outputs ==================
output "should" be this
................................................
Inside FuncA( )
printf Addr of FuncA( ) is 0x40100A
cout Addr of FuncA( ) is 0x0040100A
.................................................
but instead I get two other outputs depending on whether
I run the app from command shell viewing output
OR
I run the app from command shell redirecting output to txt file
both scenarios shown below.

*------- running from command shell and viewing output

Inside FuncA( ) <-correct
printf Addr of FuncA( ) is 0x40100A <-correct
Inside FuncB( ) <-? not correct should print last ?
cout Addr of FuncA( ) is 0x0040100A <-? not correct should print third ?

*------- end command shell viewing output

*_____ running from command shell and redirecting output to txt file

cout Addr of FuncA( ) is 0x0040100A <-? not correct should print third ?
Inside FuncA( ) <-? not correct should print first ?
printf Addr of FuncA( ) is 0x40100A <-? not correct should print second ?
Inside FuncB( ) <-? not correct should print last ?

*________ end redirection to file
 
F

Francesco S. Carta

I am newbee novice programmer, and I ran across some strange outputs
in an app I was creating that I could not understand. So I reproduced the
strangeness in this very small app for posting. It must have something
to do with mixing printf and cout together in the same
function, which it appears one should not do that. I'm sure you will
know what is going on but I have never ran across this before. I am
compiling with MS VS 6.0 (and old version)
Appreciate any comments or input.

I'm sorry I wasn't able to compile your code, nonetheless I can give you
some indications about improving it.

First of all you should drop VS6, the latest version is available for
free (2010).

Also, find the C++ FAQ and set apart some time to read the introductory
sections at the very least, that will give you a good direction about
doing "good C++"

I'll interleave some other comments to your code without giving any kind
of rationale, as you'll find them better explained in the C++ FAQ.
===== entire small app code below, outputs to follow ============
#include <windows.h>
#include <stdio.h>
#include <iostream.h>

Include the extension-less versions said:
struct Hold {
DWORD pHeld; } *pHold;

Use proper source code formatting and consider separating the struct
definition from the pointer declaration.
void FuncA( ); void FuncB( );
void main( ) {

main() _must_ return an int
DWORD FuncA_addr = (DWORD)FuncA; __asm

Don't use C style casts, there are better (explicit, self explaining and
more visible) casts in C++
{ push [FuncA_addr]
pop [pHold] } FuncA( );

Avoid using assembly unless in case you have no other choice. For
instance, I have no idea of what the above chunk of code does, and as I
am in a C++ group, I am not expected to have such knowledge.
FuncB( );
}

void FuncA( )
{
printf("Inside FuncA( )\n");
printf("printf Addr of FuncA( ) is 0x%X\n", pHold);

Don't use C input/output functions unless you really have to, just do it
the C++ way.

Don't take me bad for omitting all explanations, you will learn more by
reading the FAQ, and pay particular attention to FAQ 5.8, for the next
time you'll have to ask for help here, as following its guidelines will
ensure you proper attention and better help.

Have good time learning C++
 
R

RB

Thanks guy, that fixed it. All I changed was this
----------------
// #include <stdio.h>
// #include <iostream.h>
#include <cstdio>
#include <iostream>
.........
..........
...........
// and then added the "std" in instead of, using namespace std;
std::cout << "cout Addr of FuncA() is " << pHold << "\n";
...........
...........
And now everything prints like it should.

Inside FuncA( )
printf Addr of FuncA( ) is 0x401195
cout Addr of FuncA( ) is 00401195
Inside FuncB( )
.......................................................
So I have been using the wrong includes. Thanks for all your suggestions !
 
F

Francesco S. Carta

Thanks guy, that fixed it. All I changed was this
----------------
// #include <stdio.h>
// #include <iostream.h>
#include <cstdio> #include <iostream>
........
.........
..........
// and then added the "std" in instead of, using namespace std;
std::cout << "cout Addr of FuncA() is " << pHold << "\n";
..........
..........
And now everything prints like it should.

Inside FuncA( )
printf Addr of FuncA( ) is 0x401195
cout Addr of FuncA( ) is 00401195
Inside FuncB( )
......................................................
So I have been using the wrong includes. Thanks for all your suggestions !

You're welcome, but please don't skip all the other suggestions I have
pointed out just because the first modification solved the issue at hand.

Updating your compiler and reading the FAQ are two very important
thrusts for your learning. Also consider reading some of the books
suggested by the FAQ.

Good luck!
 
R

ralph

Thanks guy, that fixed it. All I changed was this
----------------
// #include <stdio.h>
// #include <iostream.h>
#include <cstdio>
#include <iostream>
........
.........
..........
// and then added the "std" in instead of, using namespace std;
std::cout << "cout Addr of FuncA() is " << pHold << "\n";
..........
..........
And now everything prints like it should.

Inside FuncA( )
printf Addr of FuncA( ) is 0x401195
cout Addr of FuncA( ) is 00401195
Inside FuncB( )
......................................................
So I have been using the wrong includes. Thanks for all your suggestions !

I thought about providing that suggestion in response to your initial
post to comp.lang.c, but held back since I assumed you would receive a
more complete answer in this group. (Also I was distracted by troubles
in posting.) In addition I noticed you had said "an old version" and
assumed you were stuck for some reason to using the older C++
libraries.

[See what trouble one gets into when they assume. <g>]

MS VS6 was released during a sea-change within C++ from C++ standard
class libraries (headers with .h extension) to C++ standard template
libraries (headers with no extensions), thus both were included. There
are several subtle differences, two of which you have already
discovered; the STL defines 'sync_with_sdio' to true by default
(insuring both libraries are using the same stream), and they are
packaged into their own namespace (insuring members are properly
referenced and not confused with other standard library calls).

There is a slight advantage to having both libraries available. Later
on when you are studying templates, it is interesting to go back and
compare what 'classes' look like compared to the 'templates'. But that
is about it - unless you have a need to support legacy code. <g>

[Note: MS actually provided both libraries. Many other compilers at
the time merely provided new headers that slapped on a namespace then
redirected to the older libraries. Some newer compilers simply do the
reverse for old headers.]

Mr. Carta has a good suggestion. If you merely want to learn C++, or
have no need to support legacy applications (using MFC, ATL, creating
ActiveX components, etc.) then you can download the newer MS VC++
compiler for free. That way you can be sure you are dealing with the
latest 'n greatest and not accidently run into legacy issues again.
However, the VC6 environment is still useful, and if that is what you
have then use it.

-ralph
 
F

Francesco S. Carta

Mr. Carta has a good suggestion. If you merely want to learn C++, or
have no need to support legacy applications (using MFC, ATL, creating
ActiveX components, etc.) then you can download the newer MS VC++
compiler for free. That way you can be sure you are dealing with the
latest 'n greatest and not accidently run into legacy issues again.
However, the VC6 environment is still useful, and if that is what you
have then use it.

I think you meant "and if that is what you have *to use* then use it",
following from the introduction of your paragraph - good addition, in
such a case.

By the way, just the first name will be fine, Ralph, unless one needs to
disambiguate ;-)
 
R

RB

You were so helpful the other day thought I would reply now that
I have some time. I reworked my code for your comment if you
have time. I understand that VC 6 has some issues, to be clear
I recently bought VC 2005 pro on an academic discount and use for
anything final. But I am so used to VC 6 pro that I jump back into
it for experimental code I write. ( I learn by 40% reading and 60%
writing foo bar's). The 60% foo bar code I write is where I really
"learn" the reading. Additionally I also read ( when I get time )
Marshall Clines FAQs. Anyhow if you are wondering where the
some of the strange logistics are coming from, I am peering into the
windows and compiler CRT implementations of exception handling
but that is another story and another app with more code.
I am not a programmer (as you can tell ) but a Civil Engineering
Cad Draftsman. I write small C, C++ and intel asm routines that do
math and other items for myself at work .
----------------------------------------
#include <windows.h>

// #include <stdio.h>
// #include <iostream.h>
#include <cstdio>
#include <iostream>

//struct Hold
// {
// DWORD pHeld;
// } *pHold;

struct Hold
{
DWORD pHeld;
};

Hold *pHold; // global ptr

void FuncA( );
void FuncB( );

int main( ) // added return on main( )

//-- DWORD FuncA_addr = (DWORD)FuncA;

DWORD FuncA_addr = reinterpret_cast<DWORD>(FuncA);

//__asm
// {
// push [FuncA_addr] //put contents of FuncA_addr on stack
// pop [pHold] //copy said contents to be addr in pHold
// }
// could have done it like this,

pHold = reinterpret_cast<Hold*>(FuncA_addr);

// But wonder how I might work with intel / Amd registers in CPP
// if I wanted to.
// ( I already understand the aspect of portable code etc )

FuncA( );
FuncB( );
return 0;
}

void FuncA( )
{
//--printf("Inside FuncA( )\n");
//--printf("printf Addr of FuncA( ) is 0x%X\n", pHold);
std::cout << "cout Addr of FuncA( ) is " << pHold << "\n"
<< "usd only cout, don't mix with stdio output\n";
}

void FuncB( )
{
//--printf("Inside FuncB( )\n");
std::cout << "Inside FuncB( )\n";
}
 
R

RB

Thanks Ralph,
I am somewhat aware of everything you wrote in excellent detail.
However I saved your response since I am only "aware" enough to
be guilty of knowing better, but not actually " knowing it " enough yet.
As to the VC 6 use and the other compiler I recently bought see my
other reply to Francesco. Additionally I tried a free version awhile back
but I don't like to mess with DLL versions and the free version would
not let me compile a static exe. I believe there are a few other things the
freebee won't do but not sure.
Anyhow thanks for the reply. Always ready to listen and / or be criticized,
since being "self " taught, the newsgroup input many times sheds light I would
not see otherwise.
 
F

Francesco S. Carta

You were so helpful the other day thought I would reply now that
I have some time. I reworked my code for your comment if you
have time.

You're welcome, I'll add a couple of notes and my "formatted version" of
you code below.

But first of all, the newline issue with your posting: I see that both
the normal text and the code you posted wrasp in a really weird manner.

If it is the case, I suggest you to avoid manually breaking lines: all
of the text I'm typing right now gets wrapped automatically by my
newsreader, I only hit return twice to separate paragraphs.

As for your code, since it didn't insert a newline in a very important
place (the cstdio and iostream inclusions stashed together) and since
I'm sure you separated them in your code, I wonder if you don't have
some issue with mixed end-of-line markers (\r\n, only \n and so on).

Are you bringing code back and forth from Linux or some other OS? It may
also be that you use different editors and those editors have been set
differently.
I understand that VC 6 has some issues, to be clear
I recently bought VC 2005 pro on an academic discount and use for
anything final. But I am so used to VC 6 pro that I jump back into
it for experimental code I write. ( I learn by 40% reading and 60%
writing foo bar's). The 60% foo bar code I write is where I really
"learn" the reading. Additionally I also read ( when I get time )
Marshall Clines FAQs. Anyhow if you are wondering where the some of the
strange logistics are coming from, I am peering into the windows and
compiler CRT implementations of exception handling
but that is another story and another app with more code.

VC2005 should be way better than VC 6, the important thing is that you
are aware of its limitations and that you have other compilers at your
disposal to cross test your code.

Here below I reformatted and added some comments to your code:

//-------
#include <cstdio>
#include <iostream>
#include <windows.h>

struct Hold {
DWORD pHeld;
};

Hold *pHold; // global ptr

/* FSC: good, this way also C++ programmers who are not so accustomed to
C struct definitions will see at a glance that we have a global pointer
instantiated
*/


void FuncA();
void FuncB();

/* FSC: I prefer to omit spaces inside the empty parentheses (less
keystrokes ;-) but it's matter of tastes
*/

int main() {
DWORD FuncA_addr = reinterpret_cast<DWORD>(FuncA);
pHold = reinterpret_cast<Hold*>(FuncA_addr);

/* FSC: good, this kind of cast can easily be found with text searches
within source code and is easier to spot even with the bare eyes.

As a side note, there is an usage of C style casts that doesn't need to
be "ported" to C++ as an explicit cast: any time you want to convert a
variable from a type to another, where such conversion happens to be a
compatible one, you can replace the cast with a functional style
conversion, for example replace this:

(double)integral_var;

with this:

double(integral_var);

*/

FuncA();
FuncB();

return 0;
}

/* FSC: the important part is declaring main() to return an int, but
actually, since main() - as you already know - is a special function
allowed to omit the return statement, you could have left it out just
like you did in the OP
*/

using std::cout;
using std::endl;

/* FSC: I personally make wide use of using declarations and using
directives to avoid putting std:: in front of such common parts of the
STL, but I try to do that only in small self contained test programs or
inside large functions that handle lots of output.

When I design the interfaces of my classes I strive to always fully
qualify all the types I use, otherwise using typedefs when type names
become awfully long or hard to type
*/

void FuncA() {
cout << "cout Addr of FuncA( ) is " << pHold << endl;
cout << "usd only cout, don't mix with stdio output" << endl;
}

void FuncB() {
cout << "Inside FuncB( )" << endl;
}

/* FSC: I believe that using endl instead of \n is easier to spot and
maybe also easier to type (I usually have to look at the keyboard to
type the slash, while normal alphabetic characters come automatically
under my fingers).

I've also been taught that endl is almost always preferable because it
flushes the stream ensuring that characters get fully output even in
case of some problem (buffered non-self-flushing output streams that
could "eat" characters in case your program crashes and you need ALL of
your debugging output to be actually output)
*/

//-------

Have good time learning C++ and always feel free to post here if you
need further help - or even just if you want to discuss some aspect of
the language and its usage.

Cheers!
 
R

ralph

Thanks Ralph,
I am somewhat aware of everything you wrote in excellent detail.
However I saved your response since I am only "aware" enough to
be guilty of knowing better, but not actually " knowing it " enough yet.
As to the VC 6 use and the other compiler I recently bought see my
other reply to Francesco. Additionally I tried a free version awhile back
but I don't like to mess with DLL versions and the free version would
not let me compile a static exe. I believe there are a few other things the
freebee won't do but not sure.

For your problem domain try and wean yourself from VS6 and migrate to
using VC 2005 Pro full-time. Especially if you plan on mixing in
Assembly.

There have been several improvements on how _asm instructions are
translated, plus VC2005 includes the ML compiler. You write Assembly
in its own file and simply include it in your project. This is handy
as there are a ton of assembly snippets and libraries available on the
web compared to the number of converted _asm snippets and you avoid
all that conversion. (Possible before just not as convenient or as
well integrated.)

The editor is more functional, and the additional integrated
Windows/Microsoft utilities and language extensions (though violently
eschewed by gcc advocates and C++ purists <g>) will be very handy in
your environment.

-ralph
[Also, while it truly hurts to disparage a long beloved CodeView - the
new debugger is easier to use and works as a subset of WinDbg. You can
download the full suite for some really heavy-duty prying. <g>]
 
R

RB

But first of all, the newline issue with your posting: I see that both
the normal text and the code you posted wrasp in a really weird
manner.
If it is the case, I suggest you to avoid manually breaking lines: all
of the text I'm typing right now gets wrapped automatically by my
newsreader, I only hit return twice to separate paragraphs.

Hey thanks for the comments.
Hmmm you are loosing me on something. I never set my line wrap at
such a short number of chars for the very reason you speak of. Any
code of any line length at all will not show up correct, nor does any
replies back from me on code suggestions show up correctly.
Rather I keep my line length wrap set at a disp I will never run into
so that my post will print like it should. Obviously I must be misunderstanding
your connotation here.
As for your code, since it didn't insert a newline in a very important
place (the cstdio and iostream inclusions stashed together) and since
I'm sure you separated them in your code, I wonder if you don't have
some issue with mixed end-of-line markers (\r\n, only \n and so on).

Ugh you are loosing me again, I just copied this paste from my post
(on the newsgroup) that you are replying to.
///////////////////////////////////////////////////
std::cout << "cout Addr of FuncA( ) is " << pHold << "\n"
<< "usd only cout, don't mix with stdio output\n";
}

void FuncB( )
{
//--printf("Inside FuncB( )\n");
std::cout << "Inside FuncB( )\n";
///////////////////////////////////////////////
As you can see the \n is in each line and further when I run the code on
my machine the lines do wrap so I am not sure what you are referring to.
Although notwithstanding I do concede to you suggestion to use endl
(see reply further down)
Here below I reformatted and added some comments to your code:
void FuncA();
void FuncB();

/* FSC: I prefer to omit spaces inside the empty parentheses (less
keystrokes ;-) but it's matter of tastes
*/

Well this I can respond to this. It may sound stupid, but I put the
space in there for one reason only. If I leave it out, when I post on the
newsgroup the font in my newsreader makes them look like a () zero.
As a side note, there is an usage of C style casts that doesn't need to
be "ported" to C++ as an explicit cast: any time you want to convert a
variable from a type to another, where such conversion happens to be a
compatible one, you can replace the cast with a functional style
conversion, for example replace this:
(double)integral_var;

with this:

double(integral_var);

*/

Oh, ok that is interesting, I will play around with that on some things.
return 0;
/* FSC: the important part is declaring main() to return an int, but
actually, since main() - as you already know - is a special function
allowed to omit the return statement, you could have left it out just
like you did in the OP
*/

Oh ok,... to be honest I rarely write console apps for anything other
than experimenting. So I have forgotten any rules about defining main()
and I just kinda throw in a void main().
For all my "useable" apps I use MFC and I never have to define winmain().
I always define the FormView class as my baseClass since it gives me a
diverse and quick interface design.
using std::cout;
using std::endl;

/* FSC: I personally make wide use of using declarations and using
directives to avoid putting std:: in front of such common parts of the
STL, but I try to do that only in small self contained test programs or
inside large functions that handle lots of output.

Ok, good point. I have on occassion done the
using namespace std;

but since I have never really learned all the facets of namespace's yet
I tend to just stay away from in my code. It is on my "lengthy" todo list
though.
void FuncA() {
cout << "cout Addr of FuncA( ) is " << pHold << endl;
cout << "usd only cout, don't mix with stdio output" << endl;
}

void FuncB() {
cout << "Inside FuncB( )" << endl;
}

/* FSC: I believe that using endl instead of \n is easier to spot and
maybe also easier to type (I usually have to look at the keyboard to
type the slash, while normal alphabetic characters come automatically
under my fingers).

I've also been taught that endl is almost always preferable because it
flushes the stream ensuring that characters get fully output even in
case of some problem (buffered non-self-flushing output streams that
could "eat" characters in case your program crashes and you need ALL of
your debugging output to be actually output)
*/
That is a good point about the flushing, I looked it up,
_CRTIMP inline basic_ostream<char, char_traits<char> >&
__cdecl endl(basic_ostream<char, char_traits<char> >& _O)
{_O.put('\n');
_O.flush();
return (_O); }

/// I guess I will have to change my habits there. I'm glad to learn this.
Thanks again for you input. I learned at least two items I was in obvious
error on.
 
R

RB

Thanks I am looking forward to getting into 2005. It sounds like
I will like it, albeit I can already tell I will miss the old class wizard.
But alas the old class wizard did not work all the time and I still
had to do somethings on my own.
I like the bit about the more advanced assembler. I notice on the
VC 6 _asm you can really get sloppy on how you use brackets
and "dword ptr" and it will still compile (i.e. assemble) to the correct
syntax when you look at it in the debugger.
Thank you for the input !
 
F

Francesco S. Carta

Hey thanks for the comments.
Hmmm you are loosing me on something. I never set my line wrap at such a
short number of chars for the very reason you speak of. Any
code of any line length at all will not show up correct, nor does any
replies back from me on code suggestions show up correctly.
Rather I keep my line length wrap set at a disp I will never run into
so that my post will print like it should. Obviously I must be
misunderstanding
your connotation here.


Ugh you are loosing me again, I just copied this paste from my post
(on the newsgroup) that you are replying to.
///////////////////////////////////////////////////
std::cout << "cout Addr of FuncA( ) is " << pHold << "\n"
<< "usd only cout, don't mix with stdio output\n";
}

void FuncB( )
{
//--printf("Inside FuncB( )\n");
std::cout << "Inside FuncB( )\n";
///////////////////////////////////////////////
As you can see the \n is in each line and further when I run the code on
my machine the lines do wrap so I am not sure what you are referring to.
Although notwithstanding I do concede to you suggestion to use endl (see
reply further down)

Sorry for the misunderstanding: there were three points in my previous
post: one relative to your code (the fact about using endl instead of
typing \n within the string literal when inserting into streams, now
solved and put apart) and two relative to how the text of your posts
appears in my newsreader (Thunderbird) that I'll try to explain better
here below.

A practical example: in your previous post, the inclusion of the headers
appeared on a single line, just like this:

"#include <cstdio> #include <iostream>"

While, of course, you separated them correctly as I can see from the GG
version of your posting:

http://groups.google.it/group/comp.lang.c++/msg/ef7a0b74866cc8c5

Where the line above correctly reads:

"#include <cstdio>
#include <iostream>"

(excluding the quotes, of course)

So I think that you might have your code editor end the lines with just
a newline (line feed) character, while your newsreader (Outlook) might
be ending them with a carriage return / line feed sequence.

When Thunderbird parses your messages, it gets confused and stashes
together some of your lines - this is all a conjecture of mine, I'd like
to hear some third party to check if anybody else sees your messages
with weird wrapping.

The other point about the posting: you might try lowering the length of
lines you have set in Outlook: as it seems to me, you have set it around
150 columns, while you either need it around 70, or else, as my
newsreader does, set it to _not_ break lines at all and to send out the
message as "flowed".

In this way the lines will be cut only where _you_ decide and other
people will receive your paragraphs as, say, a single line of 400
characters, another of 300 chars and so on: their newsreader will then
wrap it according to the local settings.

To rephrase all the above, I think there are/were three issues:
- posting: line wrap too long
- posting: incoherent end-of-line sequences
- code (solved): using endl instead of "\n" when inserting into streams

I hope to have cleared it out, sorry for the long off topic digression
guys ;-)

Just another comment here below, I'm glad the other (snipped) comments
of mine came useful to you.

Well this I can respond to this. It may sound stupid, but I put the
space in there for one reason only. If I leave it out, when I post on
the newsgroup the font in my newsreader makes them look like a () zero.


That's a good reason, but the best solution would be to change the font
you use. Try Courier New or another monospaced font - that will ensure
you'll see the postings as the majority of people happens to see them.

If you want further clarification about all these posting issues feel
free to drop me an email, so we'll avoid cluttering the group with off
topic questions ;-)

Ah, I was about to forget: please keep the attribution lines in place
when you snip parts of the message you are replying to.

Cheers
 
M

Michael Doubez

For your problem domain try and wean yourself from VS6 and migrate to
using VC 2005 Pro full-time. Especially if you plan on mixing in
Assembly.
[snip]

The editor is more functional, and the additional integrated
Windows/Microsoft utilities and language extensions (though violently
eschewed by gcc advocates and C++ purists <g>) will be very handy in
your environment.

Which extensions ?
AFAIK, the only notable extension is SEH.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top