c++ dll issues with vb

Morcyk
Morcyk used Ask the Experts™
on
I have a dll written in c++ which works fine with no issues when using a test application in c++. There is a verbose response option as well. When I use a test application written in VB with verbose response everything works. But when I disable verbose response in the VB test application, the IDE crashes with an access violation on the SECOND time I click a submit button. It works fine the first time.

The code in the dll which appears to be the culprit is:
sTemp = new char[strlen(oXMLElem->xml) + 1]; // works
memcpy (sTemp, (char *)oXMLElem->xml, strlen(oXMLElem->xml)); // fails

// more code here

delete sTemp;

I have verified that oXMLElem is not null and contains a string of length > 0.

If further information is needed don't hesitate to ask. Not sure where to go from here.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Author of the Year 2009
Commented:
For debugging, add a temp variable:

   int nLen= strlen(oXMLElem->xml);
   sTemp = new char[ nLen + 1];
   memcpy (sTemp, oXMLElem->xml, nLen );

breakpoint and makes sure that nLen is a sane value.

Also, are you certain that oXMLElem->xml is pointer to a valid string?  What is its data type (I note that you need to coerce it to char* ) ?

Also, the actual error may be on the previous line.

-- Dan

Author

Commented:
Although making the recommended changes didn't actually correct the issue, it did lead me to the culprit. As it turned out I forgot a +1 on a memory allocation elsewhere in the code so later when I attempted to set the last byte to '\0', it was past the end of the array.

btw oXMLElem->xml returns a BSTR *

thanks for the help.
Author of the Year 2009

Commented:
Thanks.  So many people think that a construct like:

   sTemp = new char[strlen(oXMLElem->xml) + 1]; // works
is more efficient than:
  int nLen= strlen(oXMLElem->xml);
  sTemp = new char[ nLen + 1];
But the actual fact is that any compiler written after about 1985 will optimize the latter into the former and both will be equivalent.  The only difference is that with the latter, you can easily breakpoint and more easily debug and it is easier to understand.

-- Dan

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial