-
New vs Malloc again!
Okay, I am hopeless. I thought I understood the use of new, but I am doing something incorrectly.
My code works great if I use malloc, but when I change it to new and delete I get the "DAMAGE: after normal block" debug error (see attached)
Code:
BOOL CALLBACK CenterCoordinates(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
int nLen = 0;
int Decimal = 0;
int i;
LPTSTR pbuffer = NULL; //char* pbuffer = NULL;
switch(Message)
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case IDOK:
{
hdlg = GetDlgItem(hwnd,IDC_XBAR ); //(hOwner, hDialogEditField)
nLen = GetWindowTextLength(hdlg);
// if(pbuffer = (LPTSTR)new int(nLen + 1))
// if(pbuffer = (LPTSTR)new char(nLen + 1))
if(pbuffer = (LPTSTR)malloc(nLen + 1))
{
GetDlgItemText(hwnd, // handle to OWNER of the control
IDC_XBAR, // control identifier
pbuffer, // pointer to buffer for text
nLen+1 // maximum size of string + NULL term.
);
// validation goes here
subsectionData[SectionNumber].ptX[0] = strtod(pbuffer, NULL);// Center X coord of circle.
delete(pbuffer);
//free(pbuffer);
}
else
{
MessageBox (NULL, TEXT ("Memory allocation failed."),
TEXT (""), MB_ICONINFORMATION) ;
exit(-1);
}
//... more code here.
P.S. If I rem out the delete(pbuffer); line my proggy runs without choking!
-
If you're running it the way you posted it (boy, you use a lot of space!):
Code:
// if(pbuffer = (LPTSTR)new int(nLen + 1))
// if(pbuffer = (LPTSTR)new char(nLen + 1))
if(pbuffer = (LPTSTR)malloc(nLen + 1))
{
// ....
delete(pbuffer);
//free(pbuffer);
}
the problem is possibly that you allocated with malloc() and freed with delete. If you alloc with malloc() you have to release with free() and if you alloc with new you have to release with delete.
I assume you commented out the lines:
>> //if(pbuffer = (LPTSTR)new int(nLen + 1))
>> //if(pbuffer = (LPTSTR)new char(nLen + 1))
because of a compile error perhaps. It appears you are attempting to allocate an array of ints and an array of chars however your syntax is incorrect; you have to use square brackets to allocate an array with new.
ie:
pbuffer = new char[nLen + 1];
Then you would subsequently have to delete with the square brackets:
delete [] pbuffer;
Whereas if you were dealing with a single element you'd do this (no square brackets):
pbuffer = new int;
delete pbuffer;
-
Buy do I feel stupid! Maybe I need to quit mixing 12 hour work days with trying to program!
Anyway, thanks for the pointers.:D
-