473,618 Members | 3,170 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strcpy and the copy constructor

My copy constructor is crashing my program, and I can't figure out
why. I'll try to make the code listing as short as I can. Here are
the two headers:

class BreakthroughCla ss
{
public:
BreakthroughCla ss();
virtual ~BreakthroughCl ass();
BreakthroughCla ss(const BreakthroughCla ss &source);
BreakthroughCla ss& operator=(const BreakthroughCla ss &source);

protected:
char Name[256];
char Description[1024];
int LocationX;
int LocationY;
vector <unsigned int> Prereqs;

friend class TechManagerClas s;
};

class TechManagerClas s
{
public:
TechManagerClas s();
virtual ~TechManagerCla ss();

void InitializeTechs ();

private:
vector <BreakthroughCl ass> Breakthroughs;

void BreakthroughLoa dTitles(char *RCLabel);
void BreakthroughLoa dData(char *RCLabel);

//single instance, do not implement these functions
TechManagerClas s(const TechManagerClas s &source);
TechManagerClas s& operator=(const TechManagerClas s &source);
};

TechManagerClas s TechManager;

So Breakthroughs are a vector of BreakthroughCla ss contained in the
TechManagerClas s, and TechManager is a global instance of
TechManagerClas s.

When I call TechManager.Ini tializeTechs, I do this:

void TechManagerClas s::InitializeTe chs()
{
BreakthroughLoa dTitles("SCIENC E");
BreakthroughLoa dTitles("GOVERN MENT");
//and so on
}

Then:

void TechManagerClas s::Breakthrough LoadTitles(char *RCLabel)
{
int i;
char FullLabel[256];
HRSRC ResourceLocatio n;
HANDLE Resource;
LPVOID ResourcePointer ;
char* pChar; //temporary tranversing variables
BreakthroughCla ss NewBreakthrough ;
char OutputString[1024];

i = 0;
while (1)
{
sprintf (FullLabel, "%s_%d", RCLabel, i);
sprintf(OutputS tring, "Loading %s Technology Breakthrough",
FullLabel);
OutputDebugStri ng(OutputString );
ResourceLocatio n = FindResourceEx (NULL, RT_RCDATA, FullLabel,
MAKELANGID(LANG _NEUTRAL, SUBLANG_NEUTRAL ));
if (ResourceLocati on == NULL)
break;
Resource = LoadResource (NULL, ResourceLocatio n);
ResourcePointer = LockResource(Re source);

pChar = (char*)Resource Pointer;
strcpy(NewBreak through.Name, pChar);
OutputDebugStri ng(NewBreakthro ugh.Name);
Breakthroughs.p ush_back(NewBre akthrough);
i++;
}
sprintf(OutputS tring, "Loaded %i %s Technology Breakthroughs", i,
RCLabel);
OutputDebugStri ng(OutputString );
}

So I'm finding the entry in my resource file (which are named
SCIENCE_0, SCIENCE_1, GOVERNMENT_0, GOVERNMENT_1, and so on), copying
the name into my temporary NewBreakthrough variable, then doing a
push_back into Breakthroughs. This calls my copy constructor, and
here's where I have problems. I took everything out (for now) except
the one line, and this is the line causing the crash.

BreakthroughCla ss::Breakthroug hClass(const BreakthroughCla ss &source)
{
strcpy (Name, source.Name);
}

I've done OutputDebugStri ng on the Name entries right into the copy
constructor, and it seems to be coming out fine (I get the name of the
techs), so I don't see why the strcpy is crashing. What am I doing
wrong?

Thanks,

Ron
Jul 22 '05 #1
8 3304
RonHiler wrote:
My copy constructor is crashing my program, and I can't figure out
why. [...]

BreakthroughCla ss::Breakthroug hClass(const BreakthroughCla ss &source)
{
strcpy (Name, source.Name);
What's 'Name'? Where does it point to?
}

I've done OutputDebugStri ng on the Name entries right into the copy
constructor, and it seems to be coming out fine (I get the name of the
techs), so I don't see why the strcpy is crashing. What am I doing
wrong?


You're using character pointers when you should use 'std::string'.

V
Jul 22 '05 #2

"RonHiler" <rh****@rjcyber ware.com> wrote in message
news:95******** *************** ***@posting.goo gle.com...
Resource = LoadResource (NULL, ResourceLocatio n);
ResourcePointer = LockResource(Re source);

pChar = (char*)Resource Pointer;
strcpy(NewBreak through.Name, pChar);
OutputDebugStri ng(NewBreakthro ugh.Name);

BreakthroughCla ss::Breakthroug hClass(const BreakthroughCla ss &source)
{
strcpy (Name, source.Name);
}

I've done OutputDebugStri ng on the Name entries right into the copy
constructor, and it seems to be coming out fine (I get the name of the
techs), so I don't see why the strcpy is crashing. What am I doing
wrong?


Is it possible that the string array of characters pointed to by pChar above
isn't null-terminated, but has some garbage after it that isn't shown by
your OutputDebugStri ng call? If so, then there's a possibility that strcpy
has trashed memory. Alternatively, have you checked what's in source.Name
inside the copy constructor? Perhaps something is wrong with the string (or
the object itself) at that point?

-Howard
Jul 22 '05 #3
"RonHiler" <rh****@rjcyber ware.com> wrote in message
news:95******** *************** ***@posting.goo gle.com...
My copy constructor is crashing my program, and I can't figure out
why. I'll try to make the code listing as short as I can. Here are
the two headers:


Since you delcare Name as a char array the default copy constructor will
work fine, it you change name to pointer then all bets are off. Also as
mentioned elsewhere use std::string

#include <iostream>
#include <cstring>

class Test
{
public:
Test(char *fred) { std::strncpy(da ta, fred, sizeof(data)-1); };
void display() const { std::cout << data << std::endl; };
void change(char *fred) { std::strncpy(da ta, fred, sizeof(data)-1); };
private:
char data[256];

};

int main()
{
Test t1("string 1");
Test t2("string 2");

t1.display();
t2.display();
t2=t1;

t1.display();
t2.display();

t1.change("new string");
t1.display();
t2.display();

return 0;
}
Jul 22 '05 #4
"Howard" <al*****@hotmai l.com> wrote in message news:<1P******* **************@ bgtnsc04-news.ops.worldn et.att.net>...

Is it possible that the string array of characters pointed to by pChar above
isn't null-terminated, but has some garbage after it that isn't shown by
your OutputDebugStri ng call? If so, then there's a possibility that strcpy
has trashed memory. Alternatively, have you checked what's in source.Name
inside the copy constructor? Perhaps something is wrong with the string (or
the object itself) at that point?


Yeah, I looked at those possibilities, and it would seem to make
sense, but I just don't see how it can be possible. Here is one entry
from my resource file as an example:

SCIENCE_0 RCDATA //BREAKTHROUGH
BEGIN
"Chemistry\ 0",
"Chemistry breakthrough description to be written...\0",
0, 0, //LOCATION IN TECH TREE
1, //NUMBER OF PREREQS
"Physics\0" //PREREQ LIST
END

Clearly my strings are null terminated. This seems to be born out by
the OutputDebugStri ngs, which aren't showing any problems. I checked
the strlen(), to see if there were characters not showing up with ODS,
but the ODS output seemed perfectly normal. Here is a snippet of what
I got:

ODS: Loading SCIENCE_0 Technology Breakthrough Process MDestiny.exe
(0xD34)
ODS: Chemistry Process MDestiny.exe (0xD34)
ODS: Chemistry 9 Process MDestiny.exe (0xD34)
ODS: Loading SCIENCE_1 Technology Breakthrough Process MDestiny.exe
(0xD34)
ODS: Physics Process MDestiny.exe (0xD34)
ODS: Physics 7 Process MDestiny.exe (0xD34)
ODS: Loading SCIENCE_2 Technology Breakthrough Process MDestiny.exe
(0xD34)
ODS: Loaded 2 SCIENCE Technology Breakthroughs Process MDestiny.exe
(0xD34)

The first line shows the name of the resource entry being parsed
The second line shows the technology name entry at the
BreakthroughLoa dTitles() level (in the temporary NewBreakthrough
variable).
The third line is actually inside the copy constructor, checking
source.Name, with the string and its length being shown.
This repeats for the next resource entry (SCIENCE_1). Then a third
entry is parsed but not found (SCIENCE_2, which causes the break in
the while statement), and the final line lets me know there were 2
total entries parsed for that catagory.

Everything SEEMS to be exactly as it should be, right into the copy
constructor. I'm really pulling my hair out over this one :)

Ron
Jul 22 '05 #5

"RonHiler" <rh****@rjcyber ware.com> wrote in message
news:95******** *************** ***@posting.goo gle.com...
"Howard" <al*****@hotmai l.com> wrote in message
news:<1P******* **************@ bgtnsc04-news.ops.worldn et.att.net>...

Is it possible that the string array of characters pointed to by pChar
above
isn't null-terminated, but has some garbage after it that isn't shown by
your OutputDebugStri ng call? If so, then there's a possibility that
strcpy
has trashed memory. Alternatively, have you checked what's in source.Name
inside the copy constructor? Perhaps something is wrong with the string
(or
the object itself) at that point?


Yeah, I looked at those possibilities, and it would seem to make
sense, but I just don't see how it can be possible. Here is one entry
from my resource file as an example:

SCIENCE_0 RCDATA //BREAKTHROUGH
BEGIN
"Chemistry\ 0",
"Chemistry breakthrough description to be written...\0",
0, 0, //LOCATION IN TECH TREE
1, //NUMBER OF PREREQS
"Physics\0" //PREREQ LIST
END

Clearly my strings are null terminated. This seems to be born out by
the OutputDebugStri ngs, which aren't showing any problems. I checked
the strlen(), to see if there were characters not showing up with ODS,
but the ODS output seemed perfectly normal. Here is a snippet of what
I got:

ODS: Loading SCIENCE_0 Technology Breakthrough Process MDestiny.exe
(0xD34)
ODS: Chemistry Process MDestiny.exe (0xD34)
ODS: Chemistry 9 Process MDestiny.exe (0xD34)
ODS: Loading SCIENCE_1 Technology Breakthrough Process MDestiny.exe
(0xD34)
ODS: Physics Process MDestiny.exe (0xD34)
ODS: Physics 7 Process MDestiny.exe (0xD34)
ODS: Loading SCIENCE_2 Technology Breakthrough Process MDestiny.exe
(0xD34)
ODS: Loaded 2 SCIENCE Technology Breakthroughs Process MDestiny.exe
(0xD34)

The first line shows the name of the resource entry being parsed
The second line shows the technology name entry at the
BreakthroughLoa dTitles() level (in the temporary NewBreakthrough
variable).
The third line is actually inside the copy constructor, checking
source.Name, with the string and its length being shown.
This repeats for the next resource entry (SCIENCE_1). Then a third
entry is parsed but not found (SCIENCE_2, which causes the break in
the while statement), and the final line lets me know there were 2
total entries parsed for that catagory.

Everything SEEMS to be exactly as it should be, right into the copy
constructor. I'm really pulling my hair out over this one :)

Ron


Unless I missed it you never said where you are calling InitializeTechs
from. Is it possible that you are running into the so called 'static
initialization order fiasco'. In other words because you are calling
InitializeTechs from the constructor of another global variable you are
inadvertently using the Breakthroughs vector before it has been constructed?

If this sounds at all likely check out the FAQ

http://www.parashift.com/c++-faq-lit...html#faq-10.11

john
Jul 22 '05 #6
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<2t******* ******@uni-berlin.de>...

Unless I missed it you never said where you are calling InitializeTechs
from. Is it possible that you are running into the so called 'static
initialization order fiasco'. In other words because you are calling
InitializeTechs from the constructor of another global variable you are
inadvertently using the Breakthroughs vector before it has been constructed?


Thanks for the thought, but no, I call InitializeTechs from inside my
WinMain function, so that's not it :)
Jul 22 '05 #7
"Adrian" <nn**@bluedream er.com> wrote in message news:<cl******* ***@titan.btint ernet.com>...

Since you delcare Name as a char array the default copy constructor will
work fine, it you change name to pointer then all bets are off.
It does not. The defualt constructor gives the same crash. And I'm
not using the default constructor for three reasons
1) I will be changing the char arrays to pointers and using 'new' to
allocate memory for them in the copy constructor (otherwise I'll be
wasting a lot of space, as I will have about 800 techs by the end).
For now they are arrays just to keep things simple until I get this
part debugged :)
2) The class in question contains vectors (see the header for
BreakthroughCla ss), and it's been my experience that default copy
constructors do not handle vectors well.
3) I consider it bad form to use default copy constructors in ANY
case, even when it seems perfectly safe. I will either prototype them
as private (and not define the function) if the class is meant to be
singly instanced, or, when I HAVE to have a copy constructor (such as
this case where the class is used as a vector member), I create my
own.
Also as
mentioned elsewhere use std::string


for purposes of performance, I dislike std::string.

I've discovered an odd thing. Having decided the source data was fine
(based on the ODS output), I turned my attention to where the data was
going. And, as it turns out, the code seems to work just fine when I
add a single line to the constructor for TechManagerClas s

TechManagerClas s::TechManagerC lass()
{
Breakthroughs.c lear();
Breakthroughs.r eserve(100);
}

The addition of the reserve command seems to do the trick, though I'm
not sure why that should be. It appears as though the memory for the
vectors is not being allocated before the strcpy command in the CC.
Which seems very strange to me, as what I know about vectors suggests
that ought not be the case (I thought the first thing push_back() did
was allocate memory if needed).

Does someone know the reason for this? Is it because of the large
memory footprint of the class (1296 bytes per member if I calculate
that right)?

I've also considered the possibility that I'm just hiding the problem,
that in fact strcpy is still leaking (somehow) but now it has memory
space to leak into (because of the reserved space), and I'll run right
back into the same issue once I get more techs input into the resource
file. Can someone comment? :)

Thanks guys for the responses. I know it's hard to debug someone
else's code, and I appreciate the efforts.

Ron
Jul 22 '05 #8

"RonHiler" <rh****@rjcyber ware.com> wrote in message
news:95******** *************** ***@posting.goo gle.com...
"Adrian" <nn**@bluedream er.com> wrote in message
news:<cl******* ***@titan.btint ernet.com>...

Since you delcare Name as a char array the default copy constructor will
work fine, it you change name to pointer then all bets are off.


It does not. The defualt constructor gives the same crash. And I'm
not using the default constructor for three reasons
1) I will be changing the char arrays to pointers and using 'new' to
allocate memory for them in the copy constructor (otherwise I'll be
wasting a lot of space, as I will have about 800 techs by the end).
For now they are arrays just to keep things simple until I get this
part debugged :)
2) The class in question contains vectors (see the header for
BreakthroughCla ss), and it's been my experience that default copy
constructors do not handle vectors well.
3) I consider it bad form to use default copy constructors in ANY
case, even when it seems perfectly safe. I will either prototype them
as private (and not define the function) if the class is meant to be
singly instanced, or, when I HAVE to have a copy constructor (such as
this case where the class is used as a vector member), I create my
own.
Also as
mentioned elsewhere use std::string


for purposes of performance, I dislike std::string.

I've discovered an odd thing. Having decided the source data was fine
(based on the ODS output), I turned my attention to where the data was
going. And, as it turns out, the code seems to work just fine when I
add a single line to the constructor for TechManagerClas s

TechManagerClas s::TechManagerC lass()
{
Breakthroughs.c lear();
Breakthroughs.r eserve(100);
}

The addition of the reserve command seems to do the trick, though I'm
not sure why that should be. It appears as though the memory for the
vectors is not being allocated before the strcpy command in the CC.
Which seems very strange to me, as what I know about vectors suggests
that ought not be the case (I thought the first thing push_back() did
was allocate memory if needed).

Does someone know the reason for this? Is it because of the large
memory footprint of the class (1296 bytes per member if I calculate
that right)?

I've also considered the possibility that I'm just hiding the problem,
that in fact strcpy is still leaking (somehow) but now it has memory
space to leak into (because of the reserved space), and I'll run right
back into the same issue once I get more techs input into the resource
file. Can someone comment? :)

Thanks guys for the responses. I know it's hard to debug someone
else's code, and I appreciate the efforts.


I think this all points to heap corruption occurring somewhere else in your
code. push_back will allocate memory, but when you call reserve it no longer
needs to (at least not for a while). Heap corruption problems are notorious
being hard to find because they cause a crash sometime after the corruption
has actually occurred.

Is it possible for you to post a complete program that has this behaviour?
Try and cut out everything extraneous and then post the reduced program
here. Often going through this process will help you find the problem
because you'll remove some piece of code that you think has no bearing and
suddenly the problem goes away, therefore you've a pretty good idea that the
code just removed was the cause of the problem.

John
Jul 22 '05 #9

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

Similar topics

42
5751
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
15
21183
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including pointers) and for objects types call their default constructor. Any others points i should know?
18
3565
by: stroker_ace | last post by:
Hi, I wonder if anyone could point me in the direction of a discussion on the similarities and differences between the C++ String type and char* strings? The reason I ask is because I am working on a legacy application using the old C socket.h library. The send function accepts the message to be sent as a char*.
81
7284
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
302
18451
by: Lee | last post by:
Hi Whenever I use the gets() function, the gnu c compiler gives a warning that it is dangerous to use gets(). Is this due to the possibility of array overflow? Is it correct that the program flow can be altered by giving some specific calculated inputs to gets()? How could anyone do so once the executable binary have been generated? I have heard many of the security problems and other bugs are due to array overflows.
3
16798
by: kaizen | last post by:
Hi, i wrote the code in C and compiled in VC++ compiler. at that time it has thrown the below mentioned error. error C2664: 'strcpy' : cannot convert parameter 2 from 'char' to 'const char *' Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
3
14299
by: naren | last post by:
Iam not getting the correct pros and cons of the strcpy() and memcpy() some where i read for short strings strcpy is faster and for large strings memcpy is faster.. in strcpy() there is a single pass over the data...but in memcpy() there are 2 passes..one is for strlen() and another is for copying.. but how memcpy will be faster for large strings? Can anybody please clear my doubt
55
7062
by: Jake Thompson | last post by:
I need to copy a value into a char * field. I am currently doing this strcpy(cm8link.type,"13"); but I get an error of error C2664: 'strcpy' : cannot convert parameter 1 from 'const char' to 'char *'
8
4291
by: shuisheng | last post by:
Dear All, I am wondering how the default copy constructor of a derived class looks like. Does it look like class B : public A { B(const B& right) : A(right) {}
0
8150
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8650
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8593
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8303
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8453
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7124
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6098
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5552
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
1760
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.