Dynamic Memory Allocation
Hi Guys,
Just trying to figure out how to use dynamic memory allocation. I've got the following program:
Code:
int main(int argc, char *argv[])
{
char *cText;
cText = new char[5];
cText = "test11111";
qDebug() << cText;
delete[] cText;
return a.exec();
}
Question is... why does it let me assign a string of more than 5 characters to this memory location?
Re: Dynamic Memory Allocation
You are assigning a value to the pointer, not to the char array behind the pointer. Your code is equivalent to:
Code:
int main() {
char *cText = 0; // line #5
char *ptr1 = "test11111"; // line #7
char *ptr2 = new char[5]; // line #6
cText = ptr2; // line #6
cText = ptr1; // line #7
delete [] ptr1; // line #11
// cText points to ptr1 and not ptr2
}
Re: Dynamic Memory Allocation