Dear all,
I have two modules, i.e.,
main.exe and
A.dll. I have a function declared in a class, i.e.,
ClassA
in the
A.dll as follows:
char* ClassA::ReadFile(const char *szFilePath)
{
int length;
char* buffer;
if(!IsFileExist(szFilePath)) {
return NULL;
}
std::ifstream is;
is.open (szFilePath, std::ios::binary);
is.seekg (0, std::ios::end);
length = is.tellg();
is.seekg (0, std::ios::beg);
buffer = new char [length +1 ]; memset(buffer,0,length + 1);
is.read (buffer,length);
buffer[length] = '\0';
is.close();
return buffer;
}
In the
main.exe, I call the function as follows:
ClassA* pA = GetClassInstanceA();
char* pszBuffTemp = pA->ReadFile();
delete[] pszBuffTemp;
Here's the problem. When I run the
main.exe, it comes to crash at the line "delete". But everything is ok after changing the "mark line1 and mark line2" above as follows:
buffer = new char [length + 20]; memset(buffer,0,length + 20 );
That is to say, when I alloc the array 20 chars more than the real need, there's no problem. I don't know the reason why and thank you for all your attention!
#ifndef _TEXT_OUTPUT_H_
#define _TEXT_OUTPUT_H_
#ifdef _WIN32
# ifdef TEXTDLL_EXPROTS
# define TEXTDLL_API __declspec(dllexport)
# else
# define TEXTDLL_API __declspec(dllimport)
# endif
#else
# define TEXTDLL_API
#endif
#include <string>
class Iabc
{
public:
Iabc() {}
virtual ~Iabc() {}
virtual char* GetText() = 0;
};
TEXTDLL_API Iabc* GetTestIns();
#endif
#ifndef _asdfasdfasf_H
#define _asdfasdfasf_H
#include "./OutApi.h"
class abc: public Iabc
{
public:
abc(){}
~abc(){}
virtual char* GetText();
};
#endif
#include "StdAfx.h"
#include "CTest.h"
char* abc::GetText()
{
char* temp = "test code here ,if the problem still exists!";
int len = sizeof(temp) + 20;
char* pResult = new char[len];
memset(pResult, 0 ,len);
strcpy(pResult, temp);
return pResult;
}
Iabc* GetTestIns()
{
static abc a;
return &a;
}
#include "stdafx.h"
#include "OutApi.h"
#include <string>
#include <stdio.h>
#pragma comment(lib, "TextDll.lib")
int main(int argc, char* argv[])
{
Iabc* abcObj = GetTestIns();
char* pFromDll = abcObj->GetText();
delete[] pFromDll;
int a;
getchar(&a);
return 0;
}
and the callstack information is as follows:
NTDLL! 7c92120e()
NTDLL! 7c98e576()
NTDLL! 7c9822e8()
KERNEL32! 7c85f9a7()
_CrtIsValidHeapPointer(const void * 0x00431800) line 1606
_free_dbg(void * 0x00431800, int 1) line 1011 + 9 bytes
operator delete(void * 0x00431800) line 49 + 16 bytes
main(int 1, char * * 0x00530e80) line 16 + 15 bytes
mainCRTStartup() line 206 + 25 bytes
KERNEL32! 7c817077()