473,404 Members | 2,174 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

c and C++ compatibility

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_FUNCTION__, \
__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(display2, 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.close();
}

//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?
Nov 14 '05 #1
10 1287
Prashant wrote:
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>
Not a C header.
#include <fstream.h>
Not a C header; not even a C++ header.
using namespace std;
A syntax error in C.

#define MainDisplay(msg, ...) Show(__FILE__,\
__PRETTY_FUNCTION__, \


Undefined initializer

Why bother going on? No C compiler will accept this stuff, and no C++
compiler should be expected to.

Nov 14 '05 #2
Prashant wrote:
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>
Not a C header.
#include <fstream.h>
Not a C header; not even a C++ header.
using namespace std;
A syntax error in C.

#define MainDisplay(msg, ...) Show(__FILE__,\
__PRETTY_FUNCTION__, \


Undefined identifier

Why bother going on? No C compiler will accept this stuff, and no C++
compiler should be expected to.

Nov 14 '05 #3

"Prashant" <pj***@ualberta.ca> wrote in message

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?

I'm not familiar with the C++ iostream call. You need to make sure that the
log-stream object isn't being messed with in any way, also that ios::app
(whatever that is) is valid.
The most likely explanation is that your C-style string manipulation is
trashing memory.
Nov 14 '05 #4
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message news:<cd**********@newsg3.svr.pol.co.uk>...
"Prashant" <pj***@ualberta.ca> wrote in message

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?

I'm not familiar with the C++ iostream call. You need to make sure that the
log-stream object isn't being messed with in any way, also that ios::app
(whatever that is) is valid.
The most likely explanation is that your C-style string manipulation is
trashing memory.


Yeah, why does that happen? Is C style string manipulation somehow
incompatible with C++? I get strange segmentation faults elsewhere I
use C-strings for no apparent reason. I've switched to the C++ string
objects, but I want to figure how why this incompatibility exists.
Nov 14 '05 #5

"Prashant" <pj***@ualberta.ca> wrote in message

Yeah, why does that happen? Is C style string manipulation somehow
incompatible with C++?
It's not totally incompatible, but if you mix and match C and C++ strings
then you have to be careful. A C++ string can be extended, for instance,
whilst a C string needs memory explicitly reserved to allow you to add more
characters.
I get strange segmentation faults elsewhere I use C-strings for no apparent reason. I've switched to the C++ string objects, but I want to figure how why this incompatibility exists.

C makes it extremely easy to read or write to memory you don't own. For
instance the following

void foo(char *str)
{
char *copy;

copy = malloc( strlen(str) );
if(copy)
strcpy(copy, str);

...
}

forgets the terminating NUL and writes to memory you don't own. On many
systems malloc() will actually return more memory than you ask for, most of
the time, so the function will appear to work until the length of the string
is a exact power of two (maybe) when it will segfault.

I'm not saying you make exactly this mistake, but it's the kind of thing
that is extremely esay to do.
Nov 14 '05 #6
Prashant <pj***@ualberta.ca> wrote:
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message news:<cd**********@newsg3.svr.pol.co.uk>...
"Prashant" <pj***@ualberta.ca> wrote in message
>
> 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?
> I'm not familiar with the C++ iostream call. You need to make sure that the
log-stream object isn't being messed with in any way, also that ios::app
(whatever that is) is valid.
The most likely explanation is that your C-style string manipulation is
trashing memory.

Yeah, why does that happen? Is C style string manipulation somehow
incompatible with C++? I get strange segmentation faults elsewhere I
use C-strings for no apparent reason. I've switched to the C++ string
objects, but I want to figure how why this incompatibility exists.


There are probably no incompatibilities. Chances are rather that you
got it wrong and are trashing memory, i.e. write to memory you don't
own etc., as Malcolm already pointed out. At least that's the typical
reason for segmentation faults. But since you don't show the code you
are using we'll never know.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #7
Prashant wrote:
Yeah, why does that happen? Is C style string manipulation somehow
incompatible with C++? I get strange segmentation faults elsewhere I
use C-strings for no apparent reason. I've switched to the C++ string
objects, but I want to figure how why this incompatibility exists.

We gots to see some code. There's no intrinsic reason why you can't use
C-style strings successfully, so most likely you are using them
incorrectly.

Brian Rodenborn
Nov 14 '05 #8
Default User <fi********@boeing.com.invalid> writes:
Prashant wrote:
Yeah, why does that happen? Is C style string manipulation somehow
incompatible with C++? I get strange segmentation faults elsewhere I
use C-strings for no apparent reason. I've switched to the C++ string
objects, but I want to figure how why this incompatibility exists.


We gots to see some code. There's no intrinsic reason why you can't use
C-style strings successfully, so most likely you are using them
incorrectly.


C-style string functions and the functions that manipulate them are
part of the C++ language definition. C++ string objects, on the other
hand, are not part of C.

Any questions about interactions between them belong in comp.lang.c++,
not in comp.lang.c. I'm afraid we can't help you here.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message news:<cd**********@newsg2.svr.pol.co.uk>...
"Prashant" <pj***@ualberta.ca> wrote in message

Yeah, why does that happen? Is C style string manipulation somehow
incompatible with C++?

It's not totally incompatible, but if you mix and match C and C++ strings
then you have to be careful. A C++ string can be extended, for instance,
whilst a C string needs memory explicitly reserved to allow you to add more
characters.

I get strange segmentation faults elsewhere I use C-strings for no

apparent
reason. I've switched to the C++ string objects, but I want to figure how

why
this incompatibility exists.

C makes it extremely easy to read or write to memory you don't own. For
instance the following

void foo(char *str)
{
char *copy;

copy = malloc( strlen(str) );
if(copy)
strcpy(copy, str);

...
}

forgets the terminating NUL and writes to memory you don't own. On many
systems malloc() will actually return more memory than you ask for, most of
the time, so the function will appear to work until the length of the string
is a exact power of two (maybe) when it will segfault.

I'm not saying you make exactly this mistake, but it's the kind of thing
that is extremely esay to do.

I'm using new to allocate my C-strings. But you guys were right in
that its trashing memory somehow. I switched everything to use C++
strings and everything seems to work fine now. Does anybody know of a
good reference on memory allocation? I think it would be good to read
up on this since it seems like I don't really have a firm grasp of the
intricacies.
Nov 14 '05 #10
[snips]

On Mon, 26 Jul 2004 08:50:14 -0700, Prashant wrote:
void foo(char *str)
{
char *copy;

copy = malloc( strlen(str) );
if(copy)
strcpy(copy, str);

...
}
.... I'm using new to allocate my C-strings. But you guys were right in
that its trashing memory somehow. I switched everything to use C++
strings and everything seems to work fine now. Does anybody know of a
good reference on memory allocation? I think it would be good to read
up on this since it seems like I don't really have a firm grasp of the
intricacies.


Allocation isn't the problem, you do that just fine (even checking to see
if the allocation worked or not). The problem is in figuring out how much
to allocate. Consider the string literal "123" - how long is it? That
depends. strlen() says it's 3. Counting bytes says it's four: '1', '2',
'3' and '\0'. Your allocation above allocates space based on the length
of the string, but neglects space for the terminating \0.

Your only shortfall in that snippet above was confusing "length" with
"space required". You can make similar mistakes by, say, trying to
calculate the size of a struct based on the size of its members; if you
forget the padding (if any), your numbers may not reflect the real size.
Nov 14 '05 #11

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

Similar topics

4
by: Jez Naisbitt | last post by:
Hi Guys, After a break of 2 years I'm now re-visiting the world of java. I recall on my last foray that I had to stick to java 1.1 so I could deploy applets from a server and obtain maximum...
0
by: flat_ross | last post by:
If there was one thing nice about "Binary Compatibility" in VB6, it would tell you at compile time that you changed your public interface. I am looking for the same functionality in .NET. I know...
6
by: someone | last post by:
Suppose that I have a class in an assembly that is delivered to the user, what can I do to change the class so that it doesn't break the binary compatibility? That is, user application can run...
13
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...
2
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...
1
by: Vycka | last post by:
Hello, There is a enterprise web application that is based on asp.net technologies and works on Microsoft IIS. The total number of users is 850. When the load of system gets very high, the...
14
by: frostalicious | last post by:
Used VB.NET (on my client PC) to convert VB6 executable to .NET executable. Placed the .exe file on a network drive on my server. From client, ran .NET Wizards "Trust an Assembly" to make the...
2
by: Carlo | last post by:
I recently started in a new position, and I inherited an application written in VB6 that uses a bunch of DLLs and OCX controls. Version Compatibility is set to Binary at the project level, but since...
1
by: Simon Woods | last post by:
Hi I have a dll ('dll-X') which runs on top of (dependent upon) several other dlls. My build environment has a folder structure binaries compat-libs
17
by: osama178 | last post by:
Hi, What does it mean for an object to be binary compatible? And why aren't STL objects binary compatible? Any insights, links, resources for further reading are greatly appreciated. Thanks.
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...

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.