473,568 Members | 2,923 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C and C++ compatibility issue

Hi, i'm having an issue with combining functions from C and C++. I'm
trying to create a logging function that displays the file, function
and line number of the code that wants to log a certain message. The
function is called MainDisplay and outputs to a file called mylog.log.
For some reason, I SOMETIMES get a segmentation fault when I try and
open an output stream to the file. The code looks something like
this:

//file display.h
#include <stdarg.h>
#include <stdio.h>
#include <iostream>
#include <fstream.h>
using namespace std;

#define MainDisplay(msg , ...) Show(__FILE__,\
__PRETTY_FUNCTI ON__, \
__LINE__, msg, ## __VA_ARGS___);
void Show(const char* file,
const char* fcn,
int line,
char* display, ...) {

va_list va;
va_start(va, display);

char display2[256];
vsprintf(displa y2, display, va);
va_end(va);

char linestr[10];
sprintf(linestr , "%d", line);

string s = file;
s += ": function ";
s += fcn;
s += ": line ";
s += linestr;
s += ": ";
s += display2;

log_stream.open ("my_log.log ", ios::app);
log_stream << s;
log_stream.clos e();
}

//end display.h

The above would be called from any file as follows:

//file randomfile.cpp

#include "display.h"

void randomfunction( ) {
char* name = "bob";
MainDisplay("Hi , my name is %s\n", name);
}

//end randomfile.cpp

But, sometimes, and not always, I get a segmentation fault when I try
and do
log_stream.open ("my_log.log ", ios::app);
From debugging i've found that this happens if i'm calling MainDisplay
from a function that does a lot of C-style string manipulation.

Whats going on here?
Jul 22 '05 #1
7 1463
* Prashant:
The code looks something like this:


It doesn't.

Anyway, don't use "..." for variable number of arguments.

In particular it is UB with respect to non-POD C++ objects,
but it's a nasty hack anyway and the root cause of the fault.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #2
[snips]

On Tue, 20 Jul 2004 15:03:12 -0700, Prashant wrote:
//file display.h
#include <stdarg.h>
#include <stdio.h>
#include <iostream>
#include <fstream.h>
using namespace std;


Okay, step one: pick a language. <stdio.h> suggests you're using C here,
<iostream> suggests you're using C++ and <fstream.h> suggests you're using
something else entirely - Delphi? Java? I don't know, but that header is
neither C nor C++, so it's impossible to even attempt to sort out your
problem since we don't even know what language you're using, let alone its
particular requirements, oddities, etc.
Jul 22 '05 #3
"Prashant" <pj***@ualberta .ca> wrote in message
news:f1******** *************** ***@posting.goo gle.com...
Hi, i'm having an issue with combining functions from C and C++. I'm
trying to create a logging function that displays the file, function
and line number of the code that wants to log a certain message. The
function is called MainDisplay and outputs to a file called mylog.log.
For some reason, I SOMETIMES get a segmentation fault when I try and
open an output stream to the file. The code looks something like
this: <snip> But, sometimes, and not always, I get a segmentation fault when I try
and do
log_stream.open ("my_log.log ", ios::app);
From debugging i've found that this happens if i'm calling MainDisplay
from a function that does a lot of C-style string manipulation.

Whats going on here?


The code you posted uses legacy C functions that are considered dangerous by
most C and C++ programmers (vsprintf and sprintf). They are known to be
unsafe because they have no way of confining their results to the array
passed. If you use them, you may accidentally corrupt your application's
state. This could be causing your problem, but it's hard to determine if
that is the culprit since the code is incomplete and possibly not even the
code that you're using.

In any situation, it would be a good idea to stop using them. I see three
reasonable options for eliminating these calls:

a) Implement a typesafe interface (not varargs and a format string) to the
Show function. Templates might be an option. This way, you can use the
typesafe stream operators on log_stream. No temporary buffer is needed for
this option.

b) Use a FILE * and vfprintf to write to the file. No temporary buffer is
needed for this option.

c) Use the (non-standard in C++) sprintf()-like methods that take a buffer
size as an argument and will not write past the end of the destination array
passed.

Options b) and c) will not protect you from a malformed format string, but
it's still an improvement.

BTW, why would you want to open and close the file repeatedly? Why not keep
it open for the lifetime of the application?

--
David Hilsee
Jul 22 '05 #4
Kelsey Bjarnason <ke*****@xxnosp amyy.lightspeed .bc.ca> wrote in message news:<pa******* *************** ******@xxnospam yy.lightspeed.b c.ca>...
[snips]

On Tue, 20 Jul 2004 15:03:12 -0700, Prashant wrote:
//file display.h
#include <stdarg.h>
#include <stdio.h>
#include <iostream>
#include <fstream.h>
using namespace std;


Okay, step one: pick a language. <stdio.h> suggests you're using C here,
<iostream> suggests you're using C++ and <fstream.h> suggests you're using
something else entirely - Delphi? Java? I don't know, but that header is
neither C nor C++, so it's impossible to even attempt to sort out your
problem since we don't even know what language you're using, let alone its
particular requirements, oddities, etc.


fstream.h is a C++ library....
the others are C libraries.
They're both compatible with each other. Well at least to the extent
that the compiler is concerned.
The reason I'm using C here is because I wanted to use the
__PRETTY_FUNCTI ON__, __FILE__, and __LINE__ macros. I couldn't find a
C++ equivalent. I know for sure this works with purely C code without
any problems.
Jul 22 '05 #5
"David Hilsee" <da************ *@yahoo.com> wrote in message news:<3e******* *************@c omcast.com>...
"Prashant" <pj***@ualberta .ca> wrote in message
news:f1******** *************** ***@posting.goo gle.com...
Hi, i'm having an issue with combining functions from C and C++. I'm
trying to create a logging function that displays the file, function
and line number of the code that wants to log a certain message. The
function is called MainDisplay and outputs to a file called mylog.log.
For some reason, I SOMETIMES get a segmentation fault when I try and
open an output stream to the file. The code looks something like
this:

<snip>
But, sometimes, and not always, I get a segmentation fault when I try
and do
log_stream.open ("my_log.log ", ios::app);
From debugging i've found that this happens if i'm calling MainDisplay
from a function that does a lot of C-style string manipulation.

Whats going on here?


The code you posted uses legacy C functions that are considered dangerous by
most C and C++ programmers (vsprintf and sprintf). They are known to be
unsafe because they have no way of confining their results to the array
passed. If you use them, you may accidentally corrupt your application's
state. This could be causing your problem, but it's hard to determine if
that is the culprit since the code is incomplete and possibly not even the
code that you're using.

In any situation, it would be a good idea to stop using them. I see three
reasonable options for eliminating these calls:

a) Implement a typesafe interface (not varargs and a format string) to the
Show function. Templates might be an option. This way, you can use the
typesafe stream operators on log_stream. No temporary buffer is needed for
this option.

b) Use a FILE * and vfprintf to write to the file. No temporary buffer is
needed for this option.

c) Use the (non-standard in C++) sprintf()-like methods that take a buffer
size as an argument and will not write past the end of the destination array
passed.

Options b) and c) will not protect you from a malformed format string, but
it's still an improvement.

BTW, why would you want to open and close the file repeatedly? Why not keep
it open for the lifetime of the application?


I want to avoid using C code altogether if possible. I just want to
be able to get the information that can be provided by
__PRETTY_FUNCTI ON__, __LINE__ and __FILE__. Are these still safe to
use in C++?
I was opening and closing the file repeatedly because for some reason
it wasn't writing to it if I kept it open the whole time. This is a
continuously running application, and I want to be able to read the
file at anytime without having to stop the app.
And no, this isn't the actual code I was using. This is just a
shorter version that I posted up because the actual code has a lot of
error checking and file parsing that I omitted. But I isolated the
problem to this segment of code, and posted it up just as an example.
If you want I can post the entire file.
Jul 22 '05 #6
Prashant wrote:

Kelsey Bjarnason <ke*****@xxnosp amyy.lightspeed .bc.ca> wrote in message news:<pa******* *************** ******@xxnospam yy.lightspeed.b c.ca>...
[snips]

On Tue, 20 Jul 2004 15:03:12 -0700, Prashant wrote:
//file display.h
#include <stdarg.h>
#include <stdio.h>
#include <iostream>
#include <fstream.h>
using namespace std;
Okay, step one: pick a language. <stdio.h> suggests you're using C here,
<iostream> suggests you're using C++ and <fstream.h> suggests you're using
something else entirely - Delphi? Java? I don't know, but that header is
neither C nor C++, so it's impossible to even attempt to sort out your
problem since we don't even know what language you're using, let alone its
particular requirements, oddities, etc.


fstream.h is a C++ library....


No, it's not. It's not anything in C++. <fstream> (no .h) is a HEADER in
C++.
the others are C libraries.
C headers, not libraries. They are (most importantly) also C++ headers,
although deprecated.

They're both compatible with each other. Well at least to the extent
that the compiler is concerned.
The reason I'm using C here is because I wanted to use the
__PRETTY_FUNCTI ON__,
This is gcc extension, not a C construct.

__FILE__, and __LINE__ macros. I couldn't find a C++ equivalent.


Those are part of C++ as well.

What you were missing is that people were saying to use the new C++ form
of those headers:

<cstdarg>
<cstdio>
Brian Rodenborn

Brian Rodenborn
Jul 22 '05 #7
Default User <fi********@boe ing.com.invalid > wrote in message news:<41******* *******@boeing. com.invalid>...
What you were missing is that people were saying to use the new C++ form
of those headers:

<cstdarg>
<cstdio>


Okay I guess I missed that. Anyway, it makes no difference, I still
have the same problems. The documentation says that all cstdarg does
is this:

namespace std {
#include <stdarg.h>
}

same with <cstdio>
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2003
by: Rob Oldfield | last post by:
Just a quick and hopefully straightforward question.... are there any issues with web sites based on .Net not working correctly (or at all) for clients using non IE browsers (Mozilla and Firefox being the two major concerns obviously)? Thanks
6
8058
by: Scott | last post by:
The code below appears to work on the following: MAC - Safari PC - IE PC - Opera But the addition of items to the dropdown (select2) does not function in: MAC – IE
13
2681
by: Derek | last post by:
As I understand it there is a good amount of link compatibility among C compilers. For example, I can compile main.c with GCC and func.c with Sun One and link the objects using either linker (GNU or Sun). What I'm curious about is why this compatibility exists in the absence of a standard C ABI? What encourages C compiler vendors to...
2
6188
by: Dominic | last post by:
Hi everybody, I'm planning to use serialization to persist an object (and possibly its child objects) in my application. However, I'm concerned about the backward compatibility issue. I'm evaluating if we can easily resolve this issue. For example, I have a class MyClass consisting of 100 fields.
10
989
by: Jon Paal | last post by:
In version 1.x .net websites came in multiple versions. As illustrated by the sample starter kits, we saw the Visual Studio versions did not work with the code developed from just the SDK. Can anyone tell me if this incompatibility will be resolved in 2.0, or are we still faced with multiple versions of applications ? ...
70
3993
by: py | last post by:
I have function which takes an argument. My code needs that argument to be an iterable (something i can loop over)...so I dont care if its a list, tuple, etc. So I need a way to make sure that the argument is an iterable before using it. I know I could do... def foo(inputVal): if isinstance(inputVal, (list, tuple)): for val in inputVal:...
150
6438
by: tony | last post by:
If you have any PHP scripts which will not work in the current releases due to breaks in backwards compatibility then take a look at http://www.tonymarston.net/php-mysql/bc-is-everything.html and see if you agree with my opinion or not. Tony Marston http://www.tonymarston.net
4
4292
by: Maxwell2006 | last post by:
Hi, I am struggling with making my website compatible with multiple browsers and versions. Is there any tool that shows me how my pages look like in different browsers
1
1539
by: Christian Maslen | last post by:
Hi all, I have come across an issue that appears to relate to APAR IY76615: IY76615 CONNECTION WITH .NET DATA PROVIDER MAY FAIL WHEN UPGRADING TO DB2 V8 FP10 This is documented as having been fixed in fix pack 11. We upgraded the deployment target from fixpack 9 to fixpack 10 and got connection errors with our ASP.Net app....
57
4706
by: HEX | last post by:
Have a site under development which works with both IE and Mozilla Firefox. Three MAC users accessed site and two have a small problem with one page and the other recently went to the new Leopard release with Safari V3.0.4. browser. This user has big problems with a couple of pages. A couple of users have older Safari and one has Firefox. They...
0
7693
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7917
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7665
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5501
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2105
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.