PDA

View Full Version : Dynamic Memory Allocation



Atomic_Sheep
9th August 2013, 10:34
Hi Guys,

Just trying to figure out how to use dynamic memory allocation. I've got the following program:


int main(int argc, char *argv[])
{
QCoreApplication a(argc, 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?

wysota
9th August 2013, 12:40
You are assigning a value to the pointer, not to the char array behind the pointer. Your code is equivalent to:


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
}

Atomic_Sheep
18th August 2013, 11:19
Got it to work thanks.