Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how can I downsize a buffer? memcpy-Problems 1

Status
Not open for further replies.

AMosmann

Programmer
May 27, 2003
82
DE
Hi, I tried to downsize a buffer by copying the interesting content it to another, kill the first and set the pointer to the new buffer, something like

MyClass (*)instance[];

void *p;
p=new MyClass[CorrectSize];
memcpy (p, instance, CorrectSize);
//up to now it works as I like it, the debugger shows, the //copy was done: (MyClass*)p[0]=CorrectValue
delete [] instance;
//??? (MyClass*)p[0] =undefined
instance = p
//the buffer is undefined

Does anyone know why?

Thanks, Andreas

Greetings Andreas
 
Weird code ....

>>p=new MyClass[CorrectSize];
>>memcpy (p, instance, CorrectSize);
memcpy copies CorrectSize *characters* while the the allocated memory can contain CorrectSize *objects*.

Unless MyClass and character is of the same size this will not work.

/JOlesen
 
Just one more point :

In general it's dangerous to copy objects using memcpy. If the objects contains pointers to allocated memory, this memory will be gone when the objects are deleted []. The copies of the objects will have pointers to the same memory - memory that should be free'd by the destructors of the original objects.
A class copy-constructor should handle this situation, but it will not be used when the object is copied using memcpy.

/JOlesen
 
This is the answer, I tried to copy CString-objects and longs, and the CStrings are destroyed, but the pointers still point. I looked for a very fast way, cause time is critical. But if there is no way I have to copy step by step, if there is no way to shrink an existing buffer. :-<


Greetings Andreas
 
Why don't you just use a vector as container for your objects ? (Much easier to handle).

/JOlesen

 
I have not worked with vectors at all, and in this moment I cant take time for learning.
The 2nd problem is that the procedure is recursive and I had to copy the vectors many times. 'cause I don't know about the exact handling of these I am a little careful.
(in former times I played delphi - my MVC++ - game started 6 weeks ago)
Many thanks
By the way, what vectors and lists do you use - MFC or STL?
and why?


Greetings Andreas
 
I always use STL - don't really know MFC.

I can recommend the STL container classes : They can save you for a lot of tedious and error prone work.
With a very little investment, you could learn the basic stuff about these - which is sufficient for a lot of programming tasks.

/JOlesen

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top