Re: function with pointer by John
John
Fri Nov 25 01:06:29 CST 2005
"alee" <alee@discussions.microsoft.com> wrote in message
news:E986D77B-A385-4C6E-9E1A-9F6C3E855F29@microsoft.com
> John, Thanks very much.
>
> Yes, you're right. I made a mistake. The private data is char *
> ptrBookTitle instead.
>
> Do you mean I can put down the body of setTitle like the followings?
> ptrBookTitle = new char[];
No. It would be:
ptrBookTitle = new char[inTitle.length() + 1];
> strcpy(ptrBookTitle, inTitle.c_str());
> Secondly, please help me on this one.
>
> I have created a copy constructor for this class
>
> CBook::CBook(const CBook& bookObject)
> {
> ptrBookTitle = new char[strlen(bookObject.ptrBookTitle)];
You have omitted the + 1 to allow for the terminating '\0'.
If ptrBookTitle may already point to memory storing a book title, then you
will need to call delete[] before allocating new memory for ptrBookTitle to
point to, or else you will have a memory leak.
> assert(ptrBookTitle);
If using a standard compliant compiler, a failure of new will result in the
throwing of an exception, not the return of a null pointer. Moreover,
asserts only work in debug mode. Accordingly, there is no point to the
assert.
> strcpy(ptrBookTitle, bookObject.ptrBookTitle);
> mNumAuthors= bookObject.mNumAuthors;
> ptrAuthors = new string[mNumAuthors];
Once again, you need to be wary of a memory leak if a Book might already
have memory allocated for this purpose.
> assert(ptrAuthors);
See above for the use of assert to check the result of new.
> for (int i = 0; i < mNumAuthors; i++)
> ptrAuthors[i] = bookObject.ptrAuthors[i];
You are using a very strange combination of char * pointers and strings. I
strongly suggest you use strings exclusively. It will give you simpler and
less error prone code. A further step toward modern C++ style would be to
use a vector of strings rather than an array of strings.
> mBookPublisher = bookObject.mBookPublisher;
> mPublicationYear = bookObject.mPublicationYear;
> mPrice = bookObject.mPrice;
> mQuantityInStock = bookObject.mQuantityInStock;
>
> }
>
> on the driver program, I have declare CBook book2(book1); to declare
> book2 and initialize it using book1. and print the information out.
> But after the program finishes the last line of code, an error
> message shows up. Here is the message:
>
> Debug Error!
> Program: .... \debug\test.exe
> Damage: after Normal block(#146) at 0x0...
>
> I have tried to comment out the CBook book2(book1); and the print();
> the error message didn't show up. What is wrong with my code?
>
It is probably the missing + 1 referred to above that is causing this.
--
John Carson