I have the following code:
ResultItemAttributeClass theAttribute;
char* tmpObtainedValueName = (char*)obtainedValue.Name();
theAttribute.AttributeName = (char*)malloc(strlen(tmpObtainedValueName)*sizeof(char));
strcpy(theAttribute.AttributeName,tmpObtainedValueName);
string tmpObtainedValueType0 = obtainedValue.aDesc->TypeName();
char* tmpObtainedValueType = (char*) tmpObtainedValueType0.c_str();
theAttribute.AttributeType = (char*)malloc(strlen(tmpObtainedValueType) * sizeof(char));
strcpy(theAttribute.AttributeType, tmpObtainedValueType);
string tmpAttributeValue0= obtainedValue.asStr();
char* tmpAttributeValue = (char*) tmpAttributeValue0.c_str();
theAttribute.AttributeValue = (char*)malloc(strlen(tmpAttributeValue) * sizeof(char));
strcpy(theAttribute.AttributeValue, tmpAttributeValue);
ResultItemAttributeClass is declared as:
struct DLLDIR ResultItemAttributeClass {
public:
char* AttributeName;
char* AttributeType;
char* AttributeValue;
};
DLLDIR is a macro for export to DLL, yes, I am creating DLL , and std::string has questionable marshalling. In the code above I am filling instance of this structure, and storing it in some array, which is contained inside another structure (it's complex, I know) But when I try to call free on it:
free(inPntr->allItems[i].allAttributes[j].AttributeName);
I get a HEAP CORRUPTION messsage:
HEAP CORRUPTION DETECTED: after Normal block (#2606781) at 0x0000021EBB4FD060.
CRT detected that the application wrote to memory after end of heap buffer.
I have looked at similar questions about HEAP CORRUPTION :
"Heap corruption detected" when using free() - author writes char beyond array boundary, but I am not modifying the value
HEAP CORRUPTION DETECTED when i try to free(void * key) - here is similar issue, but I do not see how it solves my question. Author appends '\0' to end of string too.
I tried accessing AttributeName , AttributeValue, AttributeType before calling Free, and it works.
LOG_F(INFO, "| %s %s %s", inPntr->allItems[i].allAttributes[j].AttributeName, inPntr->allItems[i].allAttributes[j].AttributeType, inPntr->allItems[i].allAttributes[j].AttributeValue);
So, how do I keep the pointer to char* from std::string , so it does not get mingled and calling free on it does not cause crash . . . ?