Click here to Skip to main content
15,900,907 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
this is my code:

void CScaricoDoc::PrintCodeZebraTesto(TCHAR *szPrinter, TCHAR *szBarcode, std::string &strPathZebra)
{
	BOOL							bRet, bEsisPrinter;
	BYTE							*pchTesto, *pchBuffOut;
	CHAR							chBarcode[256];
	TCHAR                           chDriverName[256], chDoc[256];
	size_t							nLenBarcode;
	int                             nbytes;
	WORD                            buffLen, *pLen;
	DWORD                           cbNeeded;
	FILE                            *fp;
	HDC                             hdc;
	HANDLE                          han;
	DEVMODE                         DM;
	DOCINFO                         infsta;
	PRINTER_INFO_2                  *pprint;


	CString cs(strPathZebra.c_str());

	TCHAR * szPathZebra = cs.GetBuffer();

	CStringA  chCodLeather = "230208010013";

	bRet = TRUE;
	bEsisPrinter = FALSE;
	chDriverName[0] = '\0';
	if (OpenPrinter(szPrinter, &han, NULL))
	{
		GetPrinter(han, 2, NULL, 0, &cbNeeded);                      // richiedo informazioni
		if (cbNeeded > 0)
		{
			pprint = (PRINTER_INFO_2 *)calloc(cbNeeded, sizeof(BYTE));
			if (pprint)
			{
				if (GetPrinter(han, 2, (LPBYTE)pprint, cbNeeded, &cbNeeded))
				{
					if (pprint->pDevMode)
					{
						_tcscpy_s(chDriverName, 256, pprint->pDriverName);
						memcpy(&DM, pprint->pDevMode, sizeof(DEVMODE));
						bEsisPrinter = TRUE;
					}
				}
				free(pprint);
				pprint = NULL;
			}
		}
		ClosePrinter(han);
	}

	if (bEsisPrinter)
	{		
			pchTesto = NULL;
			pchBuffOut = NULL;

#ifdef _UNICODE
			WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, szBarcode, -1, chBarcode, 256, NULL, NULL);
#else
			_tcscpy_s(chBarcode, 256, szBarcode);
#endif
			nLenBarcode = strlen(chBarcode);
		{
			nbytes = strPathZebra.size()*2;

			if (nbytes > 0)
			{
				//pchTesto = (BYTE *)calloc(nbytes + 1, sizeof(BYTE));
				CT2A temp(cs); // convert from CString to CT2A
				pchTesto = (BYTE *)(char *)temp;
				//BYTE *p = (BYTE*)(const char*)cs;
				pchBuffOut = (BYTE *)calloc(nbytes + nLenBarcode + 3, sizeof(BYTE));
				//pchTesto = pByte;
				//nbytes = (int)fread(pchFile, sizeof(unsigned char), nbytes + 1, fp);

				if (nbytes > 0)																		// Ho letto il file testo
				{
					//sprintf_s((char *)pchBuffOut + 2, nbytes + nLenBarcode + 1, /*(char *)pchTesto*/cs, chBarcode);
					sprintf_s((char *)pchBuffOut + 2, nbytes + nLenBarcode + 1, "%s%s", (char *)pchTesto, chBarcode);
					//sprintf_s((char *)cs.GetBuffer() + 2, nbytes + nLenBarcode + 1, (char *)nbytes, chBarcode);
					pLen = (WORD *)pchBuffOut;
					buffLen = (WORD)strlen((char *)pchBuffOut + 2);
					(*pLen) = buffLen;

					_tcscpy_s(chDoc, 256, _T("Label zebra"));
					std::memset(&infsta, 0, sizeof(infsta));
					infsta.cbSize = sizeof(DOCINFO);
					infsta.lpszDocName = chDoc;

					hdc = CreateDC(chDriverName, szPrinter, NULL, &DM);
					if (hdc)
					{
						StartDoc(hdc, &infsta);
						bRet = (ExtEscape(hdc, PASSTHROUGH, buffLen + 2, (LPCSTR)pchBuffOut, 0, NULL) > 0) ? FALSE : TRUE;
						EndDoc(hdc);
						DeleteDC(hdc);
					}
				}

				if (pchTesto) { free(pchTesto); pchTesto = NULL; }
				if (pchBuffOut) { free(pchBuffOut); pchBuffOut = NULL; }
			}

		}
	}
	return;
}


What I have tried:

I tried to search on internet and I read that is a loss of memory, I think it depends on pointer pchTesto and pchBuffOut..when I free up memory
Posted
Updated 25-May-23 5:55am
v4
Comments
Richard Deeming 25-May-23 3:30am    
Nobody can guess what error you're getting, nor what line it relates to.

Click the green "Improve question" link and update your question to include the full details of the error, and tell us what you have tried and where you are stuck.
Andre Oosthuizen 25-May-23 3:36am    
Your previous question from yesterday should have been a good learning curve, the more info you give us, the better the response and answer. :) I see you are updating your question now, great!
Member 14594285 25-May-23 3:42am    
yes I think it's a problem of pointers, but I don't know how I can free memory
Richard MacCutchan 25-May-23 4:04am    
You need to use rhe debugger to trace through the code. The error suggests that you are overwriting some memory that you have not allocated, and there is no way anyone here can guess where that is happening. It is also unclear why you are mixing Unicode and non-Unicode in the same function.
Shao Voon Wong 25-May-23 7:24am    
There is no need to free temp. CT2A allocates memory on the stack, not heap. When the function returns, the stack memory used by CT2A shall be freed.

Here is an example on how to use CT2A: https://stackoverflow.com/questions/859304/convert-cstring-to-const-char

First a couple of tips. ALWAYS remember to initialize pointers and buffers :
C++
BYTE                            *pchTesto = nullptr;
BYTE                            *pchBuffOut = nullptr;
WORD                            *pLen = nullptr;
FILE                            *fp = nullptr;
PRINTER_INFO_2                  *pprint = nullptr;
CHAR                            chBarcode[256] = { 0 };
TCHAR                           chDriverName[256] = { 0 };
TCHAR                           chDoc[256] = { 0 };
Second, the number 256 appears many places in your code. Repeated use of literal values is not a good practice. It is better to use a constant value like :
C++
const int BufferSize = 255;

CHAR                            chBarcode[BufferSize+1] = { 0 };
TCHAR                           chDriverName[BufferSize+1] = { 0 };
TCHAR                           chDoc[BufferSize+1] = { 0 };
I use +1 in each declaration to reserve a spot for the null terminator of the string. Then the function calls will look like this :
C++
_tcscpy_s(chDoc, BufferSize, _T("Label zebra"));

_tcscpy_s(chDriverName, BufferSize, pprint->pDriverName);
and you will always have a null-terminated string and the copy will never overflow.

One problem is this :
C++
CT2A temp(cs); // convert from CString to CT2A
pchTesto = (BYTE *)(char *)temp;
because later you try to free that memory. Check out the implementation of C2TA. It is actually a class that manages its own memory so you are trying to free an invalid memory pointer. You can also use this class to do that : CW2AEX Class | Microsoft Learn[^].

This is one example of why the STL's unique_ptr class is so useful. It automatically deletes the memory when the object falls out of scope. Here is documentation on it : https://cplusplus.com/ : unique_ptr[^]. I highly recommend that you read up on that and give it a try.
 
Share this answer
 
It is obvious that is a memory bug, so analyze your "mystory" code line. I guess that you havent provided enough memory for the API call. Read the documentation about the function in depth, because the API sometimes needs to get a memory block to fill with data and its size.

Step in single step mode in your code to find the place. Visit some debug tutorials to improve your knowledge.

Good luck ;-)
 
Share this answer
 
First check that you have allocated enough memory for the data you're working with using 'malloc'.

In your code, you have a few instances where memory is allocated (pprint, pchTesto, and pchBuffOut), but you only free pprint at the end. Make sure to free all allocated memory.

To allocate memory correctly for 'pchTesto' and 'pchBuffOut' try something like -

// Allocate memory for pchTesto
BYTE* pchTesto = nullptr;
size_t nLen = strPathZebra.size();
if (nLen > 0)
{
    pchTesto = (BYTE*)malloc(nLen + 1);
    memcpy(pchTesto, szPathZebra, nLen + 1);
}

// Allocate memory for pchBuffOut
size_t buffSize = nbytes + nLenBarcode + 3;
BYTE* pchBuffOut = (BYTE*)malloc(buffSize);


Once done, clear all memory allocations -
// Free allocated memory for pchTesto
free(pchTesto);

// Free allocated memory for pchBuffOut
free(pchBuffOut);
 
Share this answer
 
v3
Comments
Member 14594285 25-May-23 3:58am    
yes but pchTesto and pchBuffOut is type BYTE not char
Andre Oosthuizen 25-May-23 4:12am    
I have updated my answer...
Member 14594285 25-May-23 4:40am    
thanks but I solved in this way:

if (pchTesto != NULL)
{
pchTesto = NULL;
delete pchTesto;
}

if (pchBuffOut != NULL)
{
pchBuffOut = NULL;
delete pchBuffOut;
}
Richard MacCutchan 25-May-23 4:50am    
No, you did not solve it, you just hid the problem.
if (pchTesto != NULL)
{
pchTesto = NULL;
delete pchTesto;
}

1. You destroy the pointer before you call delete on it, so there is nothing to delete.
2. You cannot use delete on a pointer that was created by malloc/calloc, you must use free. And you mustr call free before you set the pointer to null.

And the issues is most likely, as I suggest above, that you are corrupting memory on the heap. The error is most likely occurring when you actually make the call to free.
Member 14594285 25-May-23 5:52am    
yes but in this way it's the same thing as before..and software crashes

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900