Buffer Memory Allocation

Here is my code, question to follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char szNoMem[]="Unable to allocate memory. Operation cancelled!";

	HWND hBox=GetDlgItem(hPrintWnd, iBox);
	
	int iLength=GetWindowTextLength(hBox);

	PTSTR szBuffer=(PTSTR) malloc( (iLength + 1) * sizeof(char) );

	if( szBuffer==NULL )
	{
		MessageBox(hPrintWnd, szNoMem, szAppName, MB_ICONEXCLAMATION);
		return FALSE;
	}

	GetWindowText(hBox, szBuffer, iLength+1);


In my very last statement, i.e., GetWindowText(), you'll notice that the length of text that I am retrieving is iLength+1. That is the SAME amount of buffer space I've alloted.

I have had zero problems with this, but I'm wondering if with my GetWindowText() I should only be getting iLength, or am I doing it right by getting iLength+1?
Last edited on
closed account (1vRz3TCk)
You are doing it correctly with iLength+1 as iLength (from GetWindowTextLength) is the number of char without the null termination.
Okay, thanks for clarifying it for me.
Topic archived. No new replies allowed.