Size of array stupidly big (Dynamic memory allocation)

Hey all, I'm trying to create an array of characters from a CString. When ever I go to allocate memory for the array of characters, it is stupidly big and clearly isn't the size of the string. Here is the code I have at the minute

1
2
3
4
5
6
7
8
CString inputString;
	GetDlgItemText(IDC_INPUTFIELD, inputString);

	int size = inputString.GetLength();

	char* outputArray;

	outputArray = new char[size];


What am I doing that its not working as expected? Thanks in advance!
char arrays are expected to be null terminated. If you don't end them with a null chracter (0, or '\0') code that uses them, like print statements, have no way to know where the string data actually ends so they will print garbage until they come across a null.

You should be allocating length + 1 chars, and the last char (after the string data) should be a literal 0.
Interesting....

That's solved my problem completely, thanks. What makes it that character strings need to be terminated with a null character?

I understand that to convert a character array to a string it needs to have a null character at the end to terminate the string cause that's how they work, but that's not what I was doing (I was just using an array, which I thought knew their size and so knew when to end etc)

What makes it so character arrays have to be an exception and use a null at the end?

That's just how character arrays are defined. They use the null character as a terminator. Arrays in C/C++ do not know their own size; they are just a section of contiguous memory. In fact, the [] operator on arrays is just syntactic sugar for pointer addition and dereferencing, and just like pointers you can freely attempt too access memory you don't own.
Oh ok. Thanks very much for taking the time to explain!
Topic archived. No new replies allowed.