I know that variable-length arrays (VLAs) are technically not allowed in C++. However, unless you use the -pedantic
keyword you do not get a warning. And even then, you only get a warning.
Though I have not found a specific reference on this, I am pretty sure VLAs
are allocated on the stack while dynamic arrays are allocated on the heap.
When debugging a function which was receiving messages of usually less than 100 mb I ran into a case when the middle of the array could not be accessed using gdb, while both the beginning and the end could. I realize that when allocated on the stack I might run into memory or address space limits quicker.
Why does this code segfault at so low numbers of bytes? Are there any limits to the size of VLAs? And why does the segfault happen on access, not allocation? And why can I access the end of the array using gdb (in this example code, in the other larger program I could access the start as well)?
I get the same result with clang and gcc.
# include <iostream>
# include <vector>
using std::cout;
using std::endl;
void foo_a (int n) {
/* on stack */
cout << "a: (C), n = " << n << endl;
char buffer[n]; buffer[n] = '\0';
cout << (void*)buffer << endl;
for (int i = 0; i < n; i++) {
buffer[i] = (char) i;
}
}
void foo_b (int n) {
/* on heap */
cout << "b: (C++), n = " << n << endl;
char * buffer = new char[n];
for (int i = 0; i < n; i++) {
buffer[i] = (char) i;
}
cout << (void*)buffer << endl;
delete [] buffer;
}
int main (int, char**) {
int Ns[] = { 1024, 123123, 10586239 };
for (int n : Ns) {
foo_b (n);
foo_a (n);
}
return 0;
}