C++ new operator and delete

Started by
54 comments, last by Hodgman 16 years, 6 months ago
Quote:Original post by Hacksaw2201
I'm learning what linked lists are and required to write one.


By whom?

Quote:Original post by Hodgman
That said, I don't think any of the posts telling him to just use std::list are useful. If one can't make their own linked list first, then one will probably use std::list wrongly.


Sure, and if you aren't an auto mechanic, how will you EVER learn to drive? [roll]
Advertisement
Ok. One final thought from me. My list works just fine now and I did find all the input usefull.

Ya'll were just stuck on the fact of creating a "global" link list type class to handle anything sent to the class and I wasn't trying to do that. Sorry for the confusion.

My class is set up to handle one specific structure not many. So with that in mind I know what I am sending to the class.

I'm trying to keep things simple here. You create a structure (the objects variable area) and then a class (the objects method area) and then pass the structure to the class method. Returned values are for error trapping.

That's the biggest difference between Java and C++ OOP. You can create multiple instances of a class in Java and it does the memory managing just fine for all the variables but with C++ allocation between object structures and class methods needs (unless you want to get into some rough code) to remain seperate otherwise you get some odd behavior.

Maybe I'm just old school. :-)
Quote:Original post by Hacksaw2201
C++ allocation between object structures and class methods needs (unless you want to get into some rough code) to remain seperate otherwise you get some odd behavior.


Er, wha?
Quote:Original post by Hacksaw2201
Ok. One final thought from me. My list works just fine now and I did find all the input usefull.

Ya'll were just stuck on the fact of creating a "global" link list type class to handle anything sent to the class and I wasn't trying to do that. Sorry for the confusion.

My class is set up to handle one specific structure not many. So with that in mind I know what I am sending to the class.

I'm trying to keep things simple here. You create a structure (the objects variable area) and then a class (the objects method area) and then pass the structure to the class method. Returned values are for error trapping.

That's the biggest difference between Java and C++ OOP. You can create multiple instances of a class in Java and it does the memory managing just fine for all the variables but with C++ allocation between object structures and class methods needs (unless you want to get into some rough code) to remain seperate otherwise you get some odd behavior.

Maybe I'm just old school. :-)


wtf? You are seriously living outside of reality.

You may not know much, but god damnit you're confident. God speed sir.
Quote:Original post by Hacksaw2201
Ok. One final thought from me. My list works just fine now and I did find all the input usefull.
Even though you ignored most of the input? You sure it works properly? Got unit tests?
Quote:Ya'll were just stuck on the fact of creating a "global" link list type class to handle anything sent to the class and I wasn't trying to do that. Sorry for the confusion.
True, a few people gave good suggestions about templating it which you aren't yet competent enough to do. However, don't turn this around on others being the one with the problem. If you don't want to take the advice then that doesn't mean the advice was bad.
Quote:My class is set up to handle one specific structure not many. So with that in mind I know what I am sending to the class.
Sure okay, but that does not mean that using a memcpy is right for copying objects.
Quote:I'm trying to keep things simple here. You create a structure (the objects variable area) and then a class (the objects method area) and then pass the structure to the class method. Returned values are for error trapping.
People here for the most part aren't trying to make things complicated, they're simply trying to help you make them correct. Whether you choose to accept it or not, you write very buggy code.
Quote:That's the biggest difference between Java and C++ OOP. You can create multiple instances of a class in Java and it does the memory managing just fine for all the variables but with C++ allocation between object structures and class methods needs (unless you want to get into some rough code) to remain seperate otherwise you get some odd behavior.
So you've dirtied your hands with C++ now eh? That doesn't mean you know much at all about the language. This 'odd behaviour' you speak of is your own attempt to convince yourself that your code wasn't buggy, and just blame the language. You're the only one being convinced of that. Memory allocation in C++ works just fine.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Okay, you're just trying to create a Linked List that works for only one type of held variable. That's actually really easy, and none of this seperating function and object allocations has anything to do with it.

- In C++, if you use new to allocate an object, the run-time puts the object on a memory structure called the heap.

- The heap for an application is automatically cleaned up only when you exit your application. This is different than java, where all classes must be new'd, and the garbage collector cleans up that memory when there are no more references.

- The pointer you get from a new is a number that references the memory allocated for the object. Pointers have the following states
- NULL. Points to nothing, safe to delete, unsafe to call operations on it
- Valid. Points to a constructed object. Safe to call delete, safe to call operations on it.
- Deleted. Points to memory that has been returned to the heap. Unsafe to call delete or call operations on it.
- Invalid. Points to memory that isn't what the pointer says it is. Unsafe.

- delete, then, needs a pointer to either NULL or a valid object to work. delete is the only way to return memory to the heap. If you no longer need an object created with new, call delete on the pointer that refers to it.

Now, with regard to your code in the original post:
- Comparing pointers just compares the number in the pointer, not the objects it refers to.

What you do is this:

1) You pass in a pointer to an object to be inserted. (let's say its pointer's value is 1)
inObject == 1
2) You check all of your nodes until the you find the tail node in the list (refers to NULL as the next object).
3) You Copy the inserted object (incorrectly, as has been pointed out, use the copy constructor for this, or if neccessary, use the clone idiom).
- the copied object is in a new memory location, indicated by it's pointer.
newObject ==2;
4) You set the pointer of the old tail node to newObject, whose value is 2.

Later, you try to delete.

Assuming you pass in the same pointer as before, inObject ==1
You get to the end of the list, and never encounter an object at 1. Why? Because the pointer you actually put on the list had a value of 2. Object.Delete returns false.

The reason why this next snippet of code works is that you never actually deleted 'object'.
if ( Object.Delete(object) == FALSE ){	object->nextObject = 0;}


If you want your code to work, in Delete, compare the objects by value.
while( *(temp->nextObject) != *objectIn){     temp = temp->nextObject;}


To make that make sense, override the == operator of your Object class to measure semantic equality. If you want to use pointers (same object in memory) to allow deletion, you might consider storing the original pointer of inObject somewhere so that you can refer to it in delete.
The original post smells to me of an academic assignment set to teach basics of the language...
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.
Seems more like a troll.
-- What would Sweetness do?
Quote:Original post by Hacksaw2201
That's the biggest difference between Java and C++ OOP. You can create multiple instances of a class in Java and it does the memory managing just fine for all the variables but with C++ allocation between object structures and class methods needs (unless you want to get into some rough code) to remain seperate otherwise you get some odd behavior.

Maybe I'm just old school.


Really, having written a few million lines of code in both languages, I cannot see much difference between Java and C++ when it comes to OOP. Of course, C++ has deterministic destructors and Java has nondeterministic finalization, and all objects in Java are created on the freestore while C++ additionally has the richness of static and auomatic storage, but they're fundamentally the same.

As always, I would suggest that if you think you need to do something difficult or bizarre in C++, it's a big red flashing light saying either (a) you don't understand the problem or (2) you've got the wrong design. Either way, it's not the fault of the language and you need to back up and rethink what you're trying to do.

Really.

No, really.

Consider this: lost of linked lists written in C++ are in use each day around the world and the work with some bizarre separation of object structures and member functions. If other programmers have done it, perhaps they have just achieved a level of enlightenment you, too, can obtain. Go back to your original implementation at the beginning of this thread, reread the advide others have given you, and see if you can make it work.

You will be enriched for having done so.

Stephen M. Webb
Professional Free Software Developer

Final result. Sequence wasn't necessary to maintain but I'm sure THAT will be coming up sometime in the future.

//=========================================================================================//// Add an object to the list////=========================================================================================int CObject::Add(object_s* objectIn){	object_s*	listEntry;	object_s*	newItem;	listEntry = pObjectHead;	while(listEntry->nextObject != 0)	{		listEntry = listEntry->nextObject;	}	newItem = (object_s*)malloc(sizeof(object_s));	listEntry->nextObject = newItem;	memcpy(newItem, objectIn, sizeof(object_s));	newItem->nextObject = 0;	return TRUE;}//=========================================================================================//// Delete an object from the list////=========================================================================================int CObject::Delete(object_s* nextItem, object_s* objectIn){	object_s*	listEntry;	listEntry = pObjectHead;	while(listEntry->nextObject != 0)	{		if (listEntry->nextObject == objectIn)		{			listEntry->nextObject = objectIn->nextObject;			nextItem = listEntry;			free(objectIn);			return TRUE;		}		listEntry = listEntry->nextObject;	}	return TRUE;}// simple to addObject.Add(pNewItem);// need return pointer when traversing the listobject_s* temp = 0;// return pointer set in argument listObject.Delete(temp, next);// nothing left in list so stop iteratingif(temp == 0){     break;}// update iteration pointernext = temp;

This topic is closed to new replies.

Advertisement