Sathoshi K
Sathoshi K

Reputation: 203

C++ pointer array memory allocation vs. normal array

I was playing around in C++ and I realized that there is a significant difference between a pointer array and a regular array.

char *myString1 = new char[1];
char myString2 [3];

myString1[0] = 'a';
myString1[1] = 'b';
myString1[2] = 'c';
myString1[3] = 'd';

myString2[0]='a';
myString2[1]='b';
myString2[2]='c';
myString2[3]='d';

I am confused to as why myString1 has no problem compiling or even printing every single character with a simple for loop even though I am only initializing an initial size of 1.

However, myString2 seems to be giving me compilation errors as I have initialized a value that is outside the array bounds.

Upvotes: 0

Views: 146

Answers (1)

Paulo1205
Paulo1205

Reputation: 944

Both should cause undefined behavior. You definitely should avoid going out of bounds.

Note, however, that the two arrays are in different memory regions. myString1, being dynamically allocated at run time, resides in the free store (or heap).

myString2, on the other hand, has its space reserved by the compiler, either in automatic storage or static storage. Your example suggests that you're using automatic storage, which, in most of our common PCs, is located in the program stack. Therefore, when you mess up with myString2, there's a chance that you're corrupting the stack frame, which may cause many kinds of unexpected results, from no effect to program crash, going through silent data corruption.

Upvotes: 5

Related Questions