하기와 같이 try...catch 구문을 사용해도 에러가 발생되지 않습니다.
이유는 모르겠습니다...흑...
void testFunc()
{
char *nowstr;
char *newstr;
char temp[100] = "Borlandforum!!";
nowstr = new char[100];
memset(nowstr, 0x00, 100);
strcpy(nowstr, temp);
printf("nowstr = %s, len=%d, addr=%d\n", nowstr, (int)strlen(nowstr),(int)nowstr);
newstr = nowstr;
printf("newstr = %s, len=%d, addr=%d\n", newstr, (int)strlen(newstr),(int)newstr);
delete nowstr; <- 해제
nowstr = NULL;
printf("delete memory!!\n");
try
{
newstr[99] = '\0'; //강제로 데이터를 밀어 넣음.
}
catch(...)
{
newstr = NULL;
printf("memory acess is fail!!\n");
}
if(newstr != NULL)
{
printf("newstr = %s, len=%d, addr=%d\n", newstr, (int)strlen(newstr),(int)newstr);
delete newstr; <<<========== 여기서 유효하지 않습니다.
}
}
그래서 방법을 바꿉니다. 클래스를 사용한 방법입니다.
class CChar
{
public:
__fastcall CChar(void)
{
FSize = 0;
FChar = NULL;
}
__fastcall ~CChar(void)
{
delete [] FChar;
FChar = NULL;
FSize = 0;
}
private:
int FSize;
char *FChar;
char *__fastcall GetChar(int AIndex)
{
try
{
if(FSize <= AIndex) return NULL;
return (char *)FChar[AIndex];
}
catch(...)
{
return NULL;
}
}
public:
__property char* Char[int AIndex] = { read = GetChar, }
public:
void __fastcall SetText(char *AChar, int ASize)
{
delete [] FChar;
FChar = new char[ASize];
FSize = ASize;
memcpy(FChar, AChar, ASize);
}
}
사용은
CChar *c1, *c2;
c1 = new CChar;
c1->SetText("TEST", 4);
c2 = c1;
delete c1;
if(c2->Char[0] != NULL) delete c2;
이상 어설픈 답변입니다. *^0^*
ps. operator 연산자를 사용하면 더 멋있을텐데....
operator연산자가 익숙하지 못한 1인.. T.T