473,661 Members | 2,464 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

modifying new[]'d objects

I'm having difficulty tracking down a bug in my program and I'm
wondering if it's due to some misuse on my part of new[]'d objects.
Here's the situation. If anyone can shed some light on this, I'd be
much obliged.

I have a simple class that looks something like this (this is a rather
abbreviated version):

class TileAttributes
{
... (a few other member variables of little consequence here)
std::string m_eventName;

TileAttributes( ) : m_eventName("") {}
TileAttributes( const TileAttributes& copy) : m_eventName(cop y.m_eventName) {}
virtual ~TileAttributes () {}
TileAttributes& operator= (const TileAttributes& copy) {
m_eventName.ass ign(copy.m_even tName); }
};

I have two arrays of TileAttributes, created with the new[] operator,
and I do a lot of this sort of thing:

array1[x] = array2[y];

All the member variables of TileAttributes are integral types, except
for m_eventName. I just added the m_eventName member the other day, and
since then I've been getting crashes when modifying these arrays. I am
using gcc 4 and gdb 6.1 (via Apple Xcode) and I'm getting errors that
look like this:

malloc: *** error for object 0x166a0210: double free

These errors (usually a few of them) always precipitate a crash in the
operator=() function of TileAttributes, specifically the line where I
am doing:

m_eventName.ass ign(copy.m_even tName)

The callstack as it exists above my operator= function looks like this:

__cxa_throw
std::__throw_le ngth_error
std::string::_R ep::_S_create
std::string::_R ep::_M_clone
std::string::as sign

This problem only occurs when m_eventName.len gth() > 0. I didn't even
have a deep copy constructor or assignment operator before I added the
m_eventName member, but I added them to see if they might solve my
problem. They made it easier to pinpoint exactly where the error was
occuring, but I am still baffled. I can't see what I might be doing
wrong here.

Tim

Jul 23 '05 #1
6 1917
Tim Conkling wrote:
I'm having difficulty tracking down a bug in my program and I'm
wondering if it's due to some misuse on my part of new[]'d objects.
Here's the situation. If anyone can shed some light on this, I'd be much
obliged.

I have a simple class that looks something like this (this is a rather
abbreviated version):

class TileAttributes
{
... (a few other member variables of little consequence here)
"Of little consequence"? Are you sure? No dynamic objects?
std::string m_eventName;

TileAttributes( ) : m_eventName("") {}
TileAttributes( const TileAttributes& copy) :
m_eventName(cop y.m_eventName) {}
virtual ~TileAttributes () {}
TileAttributes& operator= (const TileAttributes& copy) {
m_eventName.ass ign(copy.m_even tName); }
};

I have two arrays of TileAttributes, created with the new[] operator,
and I do a lot of this sort of thing:

array1[x] = array2[y];

All the member variables of TileAttributes are integral types, except
for m_eventName. I just added the m_eventName member the other day, and
since then I've been getting crashes when modifying these arrays. I am
using gcc 4 and gdb 6.1 (via Apple Xcode) and I'm getting errors that
look like this:

malloc: *** error for object 0x166a0210: double free
Sounds like bad dynamic memory management. Check this out:

class Bad {
char *str;
int a;
public:
Bad(const char* s) : str(new char[strlen(s)+1]) {
strcpy(str, s);
}
~Bad() { delete[] str; }
};

class HasBad {
Bad bad;
public:
HasBad() : bad("badbadbad" ) {}
HasBad(const HasBad& hb) : bad(hb.bad) {}
};

Now copy a 'HasBad' object or pass it into a function by value, and you
going to have all kinds of problems. Is "HasBad" the culprit? No. It's
the 'Bad'. So, in what you've shown 'TitleAttribute s' is probably not
the class itself, but one of those things you think are "of little
consequence".
These errors (usually a few of them) always precipitate a crash in the
operator=() function of TileAttributes, specifically the line where I am
doing:

m_eventName.ass ign(copy.m_even tName)

The callstack as it exists above my operator= function looks like this:

__cxa_throw
std::__throw_le ngth_error
std::string::_R ep::_S_create
std::string::_R ep::_M_clone
std::string::as sign

This problem only occurs when m_eventName.len gth() > 0. I didn't even
have a deep copy constructor or assignment operator before I added the
m_eventName member, but I added them to see if they might solve my
problem. They made it easier to pinpoint exactly where the error was
occuring, but I am still baffled. I can't see what I might be doing
wrong here.


What you showed is OK. However, there is always that thing, you know,
that you didn't show. There is always doubt about it, you see...

Also, _sometimes_ (really rarely) your implementation of the standard
classes could be buggy. You could try switching to another library
implementation, but only when you exhaust all possibilities to fix your
own code.

V
Jul 23 '05 #2
On 2005-06-30 15:32:22 -0400, Victor Bazarov <v.********@com Acast.net> said:
Tim Conkling wrote:
I'm having difficulty tracking down a bug in my program and I'm
wondering if it's due to some misuse on my part of new[]'d objects.
Here's the situation. If anyone can shed some light on this, I'd be
much obliged.

I have a simple class that looks something like this (this is a rather
abbreviated version):

class TileAttributes
{
... (a few other member variables of little consequence here)


"Of little consequence"? Are you sure? No dynamic objects?
std::string m_eventName;

TileAttributes( ) : m_eventName("") {}
TileAttributes( const TileAttributes& copy) :
m_eventName(cop y.m_eventName) {}
virtual ~TileAttributes () {}
TileAttributes& operator= (const TileAttributes& copy) {
m_eventName.ass ign(copy.m_even tName); }
};

I have two arrays of TileAttributes, created with the new[] operator,
and I do a lot of this sort of thing:

array1[x] = array2[y];

All the member variables of TileAttributes are integral types, except
for m_eventName. I just added the m_eventName member the other day, and
since then I've been getting crashes when modifying these arrays. I am
using gcc 4 and gdb 6.1 (via Apple Xcode) and I'm getting errors that
look like this:

malloc: *** error for object 0x166a0210: double free


Sounds like bad dynamic memory management. Check this out:

class Bad {
char *str;
int a;
public:
Bad(const char* s) : str(new char[strlen(s)+1]) {
strcpy(str, s);
}
~Bad() { delete[] str; }
};

class HasBad {
Bad bad;
public:
HasBad() : bad("badbadbad" ) {}
HasBad(const HasBad& hb) : bad(hb.bad) {}
};

Now copy a 'HasBad' object or pass it into a function by value, and you
going to have all kinds of problems. Is "HasBad" the culprit? No. It's
the 'Bad'. So, in what you've shown 'TitleAttribute s' is probably not
the class itself, but one of those things you think are "of little
consequence".
These errors (usually a few of them) always precipitate a crash in the
operator=() function of TileAttributes, specifically the line where I
am doing:

m_eventName.ass ign(copy.m_even tName)

The callstack as it exists above my operator= function looks like this:

__cxa_throw
std::__throw_le ngth_error
std::string::_R ep::_S_create
std::string::_R ep::_M_clone
std::string::as sign

This problem only occurs when m_eventName.len gth() > 0. I didn't even
have a deep copy constructor or assignment operator before I added the
m_eventName member, but I added them to see if they might solve my
problem. They made it easier to pinpoint exactly where the error was
occuring, but I am still baffled. I can't see what I might be doing
wrong here.


What you showed is OK. However, there is always that thing, you know,
that you didn't show. There is always doubt about it, you see...

Also, _sometimes_ (really rarely) your implementation of the standard
classes could be buggy. You could try switching to another library
implementation, but only when you exhaust all possibilities to fix your
own code.

V


All the other member variables are basic built-in datatypes. There are
no complex objects and nothing is dynamically allocated. The class
looks exactly like this:

class TileAttributes
{
public:

enum CollisionType
{
kNoSides = 0,
kTopSide,
kAllSides
};

float friction;
CollisionType collisionType;
bool climbable;
unsigned short animationLength ;
unsigned short animationPause;
short collisionClassL owerBound;
short collisionClassU pperBound;
std::string collisionEventN ame;
};

Jul 23 '05 #3
Tim Conkling wrote:
[...]
All the other member variables are basic built-in datatypes. There are
no complex objects and nothing is dynamically allocated. The class looks
exactly like this:
No, it can't be. In the previous post there were two constructors,
a virtual destructor, and an assignment operator. Where did they go?
Also, there was a member called 'm_eventName'. Where is it?

So, you're not showing all the code again. What do you want us to do,
read your mind or the contents of your computer memory remotely?

class TileAttributes
{
public:

enum CollisionType
{
kNoSides = 0,
kTopSide,
kAllSides
};

float friction;
CollisionType collisionType;
bool climbable;
unsigned short animationLength ;
unsigned short animationPause;
short collisionClassL owerBound;
short collisionClassU pperBound;
std::string collisionEventN ame;
};


OK, fine. The data part probably looks like that. Please, don't take my
suggestions too literally. I said that the problem was in the code you
didn't show. Was I wrong?

Here is how I arrived to the "not here" conclusion. You said there was
a problem. You showed some code. I looked at the code shown. There was
no problem with that code. Therefore, the problem _must_ be elsewhere.
Am I being unreasonable here?

You said the error you got was "double free". That's some bad memory
management (do you agree?). It could be due to some bad memory management
in one of subobjects of TitleAttributes . Or it could be due to some bad
memory management in some other place. It still could be the 'eventName'
(or whatever you decide to call it), although I strongly doubt that. You
should check the implementation of 'std::string' though. Try an older
version of the same compiler (with its older version of the standard
classes). Or try another compiler (if you can).

V
Jul 23 '05 #4
I appreciate the help and I'm sorry for the confusion. What I meant to
say is that the _data_ portion of the class looks exactly like what I
copied-and-pasted in the previous message. I didn't include the member
functions because I had already shown what they generally looked like.

In my original message, I was attempting to save space, and I wrote
the class definition from memory. It didn't come out
character-for-character the way it appears in my header file. The point
is, there is only one member variable of note and its type is
std::string. All the other variables are built-in datatypes.

I seriously doubt the problem is with the std::string implementation,
so I'll look at other parts of the code.

Jul 23 '05 #5
Tim Conkling wrote:
[snip]
TileAttributes& operator= (const TileAttributes& copy) {
m_eventName.ass ign(copy.m_even tName); }
};


Presumably in reality this assignment operator returns something?

James
Jul 23 '05 #6
On 2005-07-01 05:53:31 -0400, James Lothian
<ja***@jameslot hian.freeserve. co.uk> said:
Tim Conkling wrote:
[snip]
TileAttributes& operator= (const TileAttributes& copy) {
m_eventName.ass ign(copy.m_even tName); }
};


Presumably in reality this assignment operator returns something?

James


Yes, it does... and I have learned my lesson about typing code from
memory. It's a bad thing, and causes all sorts of confusion when real
code is mixed in with code-off-the-top-of-my-head.

FWIW, the problem has been corrected. It was bad memory management on
my part. I was memcpy'ing an array of these objects to another array,
which worked fine back when all the objects data members were simple
data types, and obviously broke when I added the std::string member.
Stupid...

Sorry for the confusion, Victor and James.

Tail between my legs,
Tim

Jul 23 '05 #7

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

Similar topics

16
8115
by: Japcuh | last post by:
How do you write self modifying code in Java? Japcuh (Just Another Perl C Unix Hacker) http://www.catb.org/~esr/faq/hacker-howto.htm#what_is ..0. ...0 000
6
5055
by: Peter Ballard | last post by:
Whew. I hope that title is descriptive! Hi all, The python tutorial tells me "It is not safe to modify the sequence being iterated over in the loop". But what if my list elements are mutable, such as lists or objects, e.g. a = , , , ] for coord in a:
0
1170
by: Gouda Man | last post by:
Hey everyone, I'm embedding the Python interpreter within my program to use as a scripting language. However, one of the unique features of our program is the ability of the internal language to possess per-object security permissions and restricted execution. Therefore, we need to add extra "magic members" (a la __class__, __doc__, and friends) to *all* objects in Python. By editing PyClass_New, we managed to add a test member to all...
6
8311
by: qwweeeit | last post by:
Hi all, when I was young I programmed in an interpreted language that allowed to modify itself. Also Python can (writing and running a module, in-line): fNew =open("newModule.py",'w') lNew= fNew.writelines(lNew) fNew.close()
12
2201
by: pvinodhkumar | last post by:
1) char* p = "Plato"; p = 'r'; // runtime error 2) char c = "Plato"; c = 'i';// ok.Why no runtime here?Why is the contradiction? cout << c << endl;
7
1777
by: Jan Gregor | last post by:
Hello folks I want to apply changes in my source code without stopping jython and JVM. Preferable are modifications directly to instances of classes. My application is a desktop app using swing library. Python solutions also interest me. Solution similiar to "lisp way" is ideal.
9
3182
by: John | last post by:
If a value type is immutable, I guess it's threadsafe to read it? But not threadsafe to assign a new value to it (can any value type be truely immutable? Isn't assigning a totally new value to it, like doing an modification, when no references are involved? I don't know enough about CLR) At the moment the whole: lock(anobject) {
6
1551
by: MackS | last post by:
Hello everyone I am faced with the following problem. For the first time I've asked myself "might this actually be easier to code in C rather than in python?", and I am not looking at device drivers. : ) This program is meant to process relatively long strings (10-20 MB) by selectively modifying small chunks one at a time. Eg, it locates approx. 1000-2000 characters and modifies them. Currently I was doing this using a string object...
5
2631
by: IUnknown | last post by:
Ok, we are all aware of the situation where modifying the folder structure (adding files, folders, deleting files, etc) will result in ASP.NET triggering a recompilation/restart of the application. In a nutshell, I understand how this can be considered desireable by some, but I am not one of those people. My situation is that we have a root site (hosted @ http://www.mydomain.com) in the root application folder '/'.
0
8343
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
8855
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
8758
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...
0
8633
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...
1
6185
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
5653
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();...
0
4346
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
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
2
1743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.